JavaScript – Why Are Object Keys Converted to [object Object]?

javascript

This code:

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

a[b] = 111;
a[c] = 222;

console.log(a[b]);

Outputs: "222" (not "111").

Explanation:

b and c will both be converted to "[object Object]"

Can someone explain why this is?

Best Answer

[object Object] is just the string representation of an object -- that is, the result of calling b.toString() or c.toString().

Object keys are always strings, so when you say:

a[b]

JS will find the string representation of b ([object Object]), and use that. Same with c.

Related Question