I am Hack Sparrow
Captain of the Internets.

Object as JavaScript object’s Key

Can you use objects as Object keys in JavaScript?

The short answer is NO. All JavaScript object keys are strings. Even if you pass an object is a key, the object's toString() will be called on it, and the key will get the string value "[object Object]".

If the above explanation did not make things obvious for you, or you in the mood for more probing, read on.

You might be wondering "Hey I have used objects as keys before!". Well, it sure might have looked like you used objects as keys, but it was not what you thought it was. Run the following code:

var o = {};
var x = {};
o[x] = 'Chuck Norris';

You get the expected result. But something is happening behind the scenes, not obvious to you.

When you do o[x] = 'Chuck', the object x is getting 'stringified' to [object Object]. And when you do console.log(o[x]), x is again getting 'stringified' to [object Object]. But since you getting expected result for console.log(o[x]), you start to think you can actually use objects as keys.

Now get ready for the eye-opener. Run the following code:

console.log(o['[object Object]']);

There you are! You thought you were setting an object as key when actually you were setting values for the string key "[object Object]". See what happens when you try to use many objects as keys.

var o = {};
var x = {};
o[x] = 'Chuck';
o.x = 'Norris';
var y = {};
o[y] = 'Bruce';
o.y = 'Lee';

The object keys (after getting 'stringified') overwrite each other. o[x] and o[y] both are references to the string "[object Object]". o.x is a true references to key named "x" of the object o, similarly o.y. As there is no key named "z", you get undefined for console.log(o.z).

Now that you know you cannot use objects as keys in JavaScript, try answering this question: does JavaScript have associative arrays?

2 Responses to “Object as JavaScript object’s Key”

  1. Stamat says:

    Hey, these two days I’ve tinkered on this topic and I’ve written deterministic JSON stringify, hat sorts alphabetically objects properties and outputs a string.

    Also I’ve written a custom implementation of JavaScript hash table:

    I know It’s several years late, I hope to help people who stumble here to find a correct solution. Leave some feedback if you have time! Thanks 🙂

  2. X says:

    Tnx for explanations!!

Make a Comment