Search code examples
javascriptecmascript-6ecmascript-5

Is undefined allowed as Object property name?


Is this allowed in javascript ?

a = {undefined : 1}
console.log(a[undefined])

[Edit] I think I was a bit messed up with habits of python, but I actually though about this one :

a = {[undefined] : 1}
console.log(a[undefined])
Note that it works for the reason is the same : undefined is casted as a string (like any value you pass with this synthax) and you end up defining the "undefined" prop

[/Edit]

And if so, does all browsers handle it the same and is it explicitly specified in the standards ?

[Edit]

NOTE : this question was slightly different from 'undefined' variable works as key to object with 'undefined' property name even though the fundamental reason and answer are the same. I asked in a context where undefined seems ambiguous as "is it the value undefined or the string "undefined" ? ", while the linked question state clearly "undefined" as a a prop name and asks about the name collision with keyword.

...And I think it can help other programmers used to Python or other language with json-like object/dict/hash synthax

[/Edit]


Solution

  • Is this allowed in javascript ?

    Yes.

    And if so, does all browsers handle it the same

    Yes.

    is it explicitly specified in the standards ?

    No.

    It's just a consequence of undefined being converted to "undefined" when used in string context:

    console.log( ("" + undefined).toUpperCase() )