Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 547
hl037_ Avatar asked Mar 17 '26 04:03

hl037_


2 Answers

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() )
like image 156
Quentin Avatar answered Mar 19 '26 17:03

Quentin


Object property names are always strings. So whatever you pass as a property name gets converted to a string. If you pass undefined then it becomes "undefined". So this:

let obj = { undefined: 0 }
obj[undefined]

is the same as this

let obj = { undefined: 0 }
obj["undefined"]

undefined doesn't have a special meaning in that case. The same applies to null, false, true etc.

like image 31
Szab Avatar answered Mar 19 '26 18:03

Szab