1

Below is the code snippet -

var a = {};

b = {
  key: "b"
};
c = {
  key: "c"
};

a[b] = 123; // Here I am confused how object is used a key
a[c] = 456;

console.log(a[b]); // output is 456
console.log(a[c]); // output is 456

Both a[b] and a[c] is printing 456. How java script is replacing b in a[b] and c in a[c].

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Sushil Kumar
  • 159
  • 10
  • 3
    Pretty sure it is doing something akin to `b.toString()` and `c.toString()` – Sumurai8 Dec 07 '18 at 11:39
  • can you turn it into a runnable snippet for us? – mast3rd3mon Dec 07 '18 at 11:39
  • `console.log(a)` shows you what actual key value was used. (And thereby also why this is not a good idea to begin with.) – misorude Dec 07 '18 at 11:42
  • 1
    Sumurai8 is correct. Keys inside an object will get cast to strings. So when you try to use an object as a key, its .toString() method is called, returning `[object Object]`. SInce all basic objects will do that, a[b] sets the value to 123 and then using a[c] overwrites that key you just created with the new value, 456. So when you console.log( a[b] ), you get the last value that under the key `[object Object]`, namely 456. – Shilly Dec 07 '18 at 11:43
  • you could use `a[b.key]` and `a[c.key]`, it will produce `{b: 123, c: 456}` – mast3rd3mon Dec 07 '18 at 11:44

2 Answers2

2

Object property names are strings (or Symbols if you explicitly create a Symbol, which isn't the case here).

Whatever expression you try to use as a property name is implicitly cast to a string.

Any basic object will have a toString() method that returns "[object Object]" (so the two different objects will be converted to identical strings and represent the same property).

var a = {};

var b = {key : "b"};
var c = {key : "c"};

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

console.log(a[b]); // output is 456 

var property_name = b.toString();
console.log("Property name: ", property_name);
console.log("a[property_name]: ", a[property_name]);
console.log("a: ", a);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Object keys in JavaScript are treated as strings. So, as @Sumurai8 pointed out, what's really happening is:

var a = {}; // Create a map/hash

b = {key : "b"};
c = {key : "c"};

a[b] = 123; // b.toString() gives `[object Object]`
// Now, the map has: { "[object Object]": 123 }
a[c] = 456; // c.toString() gives `[object Object]`
// Now, the map has: { "[object Object]": 456 }

console.log(a[b]); // b.toString() gives `[object Object]`
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128