0

Could you please explain me what happens in code bellow? Why both of the expressions have same value?

let a = {};

let b = {
    value: 'b'
};

let c = {
    value: 'c'
};

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

console.log(a[b], a[c]); // ==> 456 456

Any link to study material are welcome

1
  • 4
    console.log(a). See what b and c used as an object property compute to. Commented Sep 5, 2019 at 6:53

4 Answers 4

3

Object keys may only be strings. When you put an object in a computed property, it will be stringified to [object Object], so a[b] is the same as a[c]: a['[object Object]'].

let a = {};

let b = {
    value: 'b'
};

let c = {
    value: 'c'
};

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

console.log(a);

So, the final assignment of 456 to the [object Object] key overwrites the prior assignment of 123 (and the resulting object only has that one key).

If you want to safely use objects as "keys", use a Map instead, whose keys can be of any type, not just strings:

const a = new Map();

let b = {
    value: 'b'
};

let c = {
    value: 'c'
};

a.set(b, 123);
a.set(c, 456);
console.log(a.get(b));
console.log(a.get(c));

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

Comments

0

Quite easy:

When you do

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

you set an object as a propery name of a.

The thing is, a property name is a string, so, toString() is called on b and c (which are objects), and that makes the same value. Do you get it?

let a = {};

let b = {
    value: 'b'
};

let c = {
    value: 'c'
};

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

console.log(a[b], a[c]); // ==> 456 456
console.log(a);

Comments

0

In a[b] = //... expression, b gets coerced to string - and the result of that conversion is a string "[object Object]". And it's the same value for c.

let a = {};

let b = {
    value: 'b'
};

let c = {
    value: 'c'
};

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

console.log(b.toString());
console.log(c.toString());

console.log(a);

Comments

0

Because Object's key can be string and you are trying to assign a object as the key, js typecasts the object to string and the key becomes [object Object] for both the objects. That is why the value is updated against the same key.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.