Does using undefined as a property key guarantee that the result will be undefined?
P粉504920992
P粉504920992 2024-01-16 23:42:26
0
1
549

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.

P粉504920992
P粉504920992

reply all(1)
P粉340980243

No, accessing obj[undefined] does not always return undefined. 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 to obj["undefined"] or obj.undefined. If such a property exists, it will return the property value, e.g. when obj = {undefined: true};.

You really should write

someField != null ? myObject[someField] : undefined;

If someField: undefined |String.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template