JavaScript object keys

JavaScript convert object keys to string

Simple principle, but as usual, the most simple rules can cause the most unexpected results.

1. Object with numbers as the key

Let’s start simple:

let o = {};
o[9] = 'a';
o['9']='b';
o[011]='c';

// All three lines are with a single key :-(

Object.keys(o) == ["9"];
o[9] == 'c';

JavaScript convert all keys into strings:

9 == '9' && 9 == 011

2. Object with objects as the key

The same principle, this time with objects, so it’s a little messier:

let o = {{}:1};

o[{first: 1}] = 1;
o[{second: 2}] = 2;

o[{first: 1}] == 1;
o["[object Object]"] == 1;

o.hasOwnProperty({something:"unexpected"}) == true;

Object.keys(o).length == 1;

3. Object with arrays as the key

And the saddest of all:

let o = {};
o.[[1,2,3]] = 'what!!!';
o["1,2,3"] == 'what!!!';

So the next time someone asks you what’s the agenda of Javascript, remember that it has a fundamental belief system about the religion of keys, and it forces it in a quite brutal way.