I'm interested in knowing what is the correct behaviour when object is accessed by undefined or null key in javascript.
I checked its behaviour in Chrome 46, Firefox 42 and node 0.12.0 and it's the same:
var obj = {};
obj[undefined] = 'foo';
obj[undefined]; // 'foo'
obj['undefined']; // 'foo'
obj; // {undefined: 'foo'}
or:
var obj = {};
obj[null] = 'foo';
obj[null]; // 'foo'
obj['null']; // 'foo'
obj; // {null: 'foo'}
Then, it seems that undefined and null are coerced to strings 'undefined' and 'null'. However if I read ecmascript specs and I see that RequireObjectCoercible is used. Reading RequireObjectCoercible specs, I see that when it is passed undefined or null as argument, it throws a TypeError exception.
Therefore I don't understand why I reproduce another behaviour when I check it.
Edit:
Thanks for Andreas and Bergi
I understand that the behaviour is this because:
12.3.2.1 Runtime Semantics: Evaluation
[...]
- Let propertyKey be ToPropertyKey(propertyNameValue).
7.1.14 ToPropertyKey ( argument )
[...]
- Return ToString(key).
7.1.12 ToString ( argument )
The abstract operation ToString converts argument to a value of type String according to Table 12:
[...]
Undefined | Return "undefined".
Null | Return "null".
Right?
obj[undefined], obj['undefined'], obj[null]the part in[ ]equals the[ Expression ]part inMemberExpression [ Expression ]. Therefor you have to have a look at4., 5., 6., 9.and10.