1

I was reading javascript questions where i found this piece of code

var a={},
    b={key:'b'},
    c={key:'c'};

a[b] = 123;
a[c] = 456;

console.log(a[b]);      // o/p - 456

can anybody make me understand this code why and how it is printing 456?

And I think we can use dot i.e a.b = 123 and string a['b'] = 123 approach to add property to an object.

2
  • 3
    b is an object, when used as key converted to string as [object Object], c is again an object which will be converted to string when used as key. This will overwrite the previous value, thus 456. Commented Sep 20, 2016 at 13:23
  • When using dot notation and bracket notation with string, you're actually adding b property on the object. Commented Sep 20, 2016 at 13:24

2 Answers 2

3

Both b and c resolve to the same string ([object Object]). Hence you are overwriting the same key.

And I think we can use dot i.e a.b = 123 and string a['b'] = 123 approach to add property to an object.

Yes you can, but a['b'] is very different from a[b]. The first one resolves to a key with a string value just as it shows ('b'), where as the other one will depend on the stringified value of the variable b (in this case is [object Object]).

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

Comments

0

For really using the content of the object, you may use the stringified version.

var a = {},
    b = { key: 'b' },
    c = { key: 'c' };

a[JSON.stringify(b)] = 123;
a[JSON.stringify(c)] = 456;

console.log(a[JSON.stringify(b)]);   

Comments

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.