2

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

[...]

  1. Let propertyKey be ToPropertyKey(propertyNameValue).

7.1.14 ToPropertyKey ( argument )

[...]

  1. 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?

1
  • 1
    In obj[undefined], obj['undefined'], obj[null] the part in [ ] equals the [ Expression ] part in MemberExpression [ Expression ]. Therefor you have to have a look at 4., 5., 6., 9. and 10. Commented Dec 19, 2015 at 12:10

1 Answer 1

1

RequireObjectCoercible is called on the base value, not on the property, before the property reference is constructed. And obj is coercible to an object :-) It does throw when you are doing stuff like undefined.x or null[y].

Sign up to request clarification or add additional context in comments.

1 Comment

One moment! When is the RequireObjectCoercible function called with an argument when ToObject is called? How it's works if I calling it so: RequireObjectCoercible(7)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.