Home  >  Q&A  >  body text

Does using undefined as a property key guarantee that the result will be undefined?

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粉504920992P粉504920992276 days ago464

reply all(1)I'll reply

  • P粉340980243

    P粉3409802432024-01-17 12:46:19

    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.

    reply
    0
  • Cancelreply