In the case of retrieving object properties through variables, that is:
myObject[someField]It is possible that
someField
(which is a string) is undefined
(possibly the result of an uninitialized string value). My experiments show that for all types of objects I can think of, the result is undefined
, which is:
anyObject[undefined] === undefined
Is this a well-known behavior, can I trust it? Can't seem to find something in the relevant documentation, my alternative is to rewrite the above as
someField ? myObject[someField] : undefined;
But I'd really prefer the concise way if it were guaranteed to return undefined
whenever we try to access the property undefined
.
No, accessing
obj[undefined]
does not always returnundefined
. Like any value used as a property name,undefined
will be cast to a string (unless it is a symbol), so it will actually access a property named "undefined".obj[undefined]
is equivalent toobj["undefined"]
orobj.undefined
. If such a property exists, it will return the property value, e.g. whenobj = {undefined: true};
.You really should write
If
someField: undefined |String
.