Javascript Object keys cannot be Objects

TL;DR – Javascript Object keys may be strings or symbols, and nothing else. So be careful when setting key/value pairs on an Object.

In Javascript, if you use an Object as another Object‘s key, you will have problems. You will not see an error, but you will be producing a bug. I ran this code sample in the node REPL to demonstrate what goes wrong.

First, I create two completely different Objects, obj1 and obj2:

> var obj1 = { a : "a" };

> var obj2 = { b : "b" };

> obj1
{ a: 'a' }
> obj2
{ b: 'b' }

Next, I create an empty Object:

> var obj3 = {};

Finally, I set two different properties on obj3. One is set on the key obj1, and the other is set on the key obj2. Since these two Objects are different, you might be fooled into thinking that obj3 will now have two keys. But watch!


> obj3[obj1] = "test1";
'test1'
> obj3
{ '[object Object]': 'test1' }
> obj3[obj2] = "test2";
'test2'
> obj3
{ '[object Object]': 'test2' }

As you can see, both the obj1 and obj2 keys have been coerced into their string values (obj1.toString() is '[object Object]', as is obj2.toString()) when the property was added. So obj3 has only one key/value pair. The first one that was added was obliterated when the second one was set.

For anyone who is more used to working with a strongly typed language, such as Java, this can be a “gotcha!” in Javascript. I certainly made this mistake, myself, when I first started coding in Javascript, years ago. If you want your keys to be less restrictive, consider using Javascript’s Map.

Leave a Reply

Your email address will not be published. Required fields are marked *