Using objects as keys in javascript, watch out!

Here is an example of using various objects as keys in . It is no problem in javascript!
Update:  I was fooled by javascript. Actually you cannot use objects as keys in standard javascript. I read the comment below from Kambhase and tested his example. It is a fact that you cannot in standard javascript use objects as keys.

Why it does not work

I read the article here: – a page where you can download a javascript which will give you code allowing you to get an implementation of Hashtables, which can use objects as keys.
Tim Down, the author of the above jshashtable code, writes amount others about why you cannot use objects as keys:

The reason for this is that JavaScript silently calls toString() on the object being passed in as the key and uses the result as the property name. In the example above, key1 and key2 both become "[object Object]", hence the second assignment simply replaces the original value of the property "[object Object]".

This also indirectly explaines why my code below seems to work: I only have one “custom object” (an object without a toString method implemented), and so run into no conflicting as Tim Down describes in the above quote.

So if you need objects as keys in a Hashtable: Use the code Tim Down have created, found here:


var a = 1.23456;
var b = new Date();
var c = { my: 'object' }
var d = function() { alert('My function') };
var arr = [];
arr[a] = (typeof a) + ' (' + a + ')';
arr[b] = (typeof b) + ' (' + b + ')';
arr = (typeof c) + ' (' + c + ')';
arr[d] = (typeof d) + ' (' + d + ')';


1.23456number (1.23456)
Sat Sep 18 18:49:18 UTC+0200 2010object (Sat Sep 18 18:49:18 UTC+0200 2010)
[object Object]object ([object Object])
function() { alert(‘My function’) }function (function() { alert(‘My function’) })

3 thoughts on “Using objects as keys in javascript, watch out!

  1. Yes, there is a problem! Let me show it to you:

    var arr= [], o= {my: “object”}, o2 = {myOther:”object”};

    arr[ o] = “foo”;
    arr.length // 0 this is bad

    arr[ o2]=”bar”;
    arr[ o] // “bar” this is even worse

    Only Strings can be used as keys. Thats why keys must be in double quotes in JSON.

  2. Hi Kambfpase,
    I have updated my blog post, and must admit that I was wrong: Javascript cannot as standard handle objects as keys. I discovered ways to get around this, one of which is to use the code of Tim Down. Read about it above.
    Thank you for your comment! :-)


Leave a Reply