-3

We know that

let obj1 = {};
obj1.x = "value";

let obj2 = {"key":"value"};
obj2[obj1] = "another value";
console.log(obj2[obj1]);

Above will print the "another value" properly on the console. Need to understand how. Does it store the address of obj1 for the key to match with the value?

3
  • 1
    "Need to understand how." - then do a console.log(obj2);, and see if that helps with the understanding. Commented Nov 29, 2021 at 9:45
  • assignment this way will simply call String(obj1) when creating the key "[object Object]" Commented Nov 29, 2021 at 9:45
  • Object keys are either strings or Symbol and anything which is not a Symbol (like your case) will be converted to a string, hence you can check that by doing: console.log(obj2[obj1.toString()]); which will give you the exact result as console.log(obj2[obj1]); Commented Nov 29, 2021 at 9:47

1 Answer 1

4

Object property names can be strings or Symbols. Anything that is not a Symbol will be converted to a string.

A plain object's toString method will convert it to "[object Object]".

You can see that string if you log the entire object.

let obj1 = {};
obj1.x = "value";

let obj2 = {"key":"value"};
obj2[obj1] = "another value";
console.log(obj2);

console.log(obj1.toString());

This does, of course, mean that if you try to set ob2[obj3] at some point, with another object, then even if obj3 is a different object it will still be converted to the same string and overwrite the previous value.

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

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.