Javascript object identities

When two things aren’t equal, but then sometimes are. This is javascript.

Easy start #

Just to get us in the mood

key1 = 3
key2 = 3
key1 == key2 // obviously true

Equality of objects is a bit more unusual

key1 = [1,2,3]
key2 = [1,2,3]
key1 == key2 // false, which is weird

key1 and key2 are different objects. That’s why they aren’t equal even though it looks like they should be. Let’s see how this can cause subtle bugs.

Associative arrays #

If the keys of an associative array are not equal, it’s normal to expect them to refer to different values. Illustrating this with a trivial example:

key1 = "home"
key2 = "work"
key1 == key2 // obviously false

phones = {}
phones[key1] = "99999999"
phones[key2] = "11111111"
phones[key1] == phones[key2] // also obviously false

So far nothing surprising.

But look at the unusual situation of keys being objects instead of strings:

key1 = [1,2,3]
key2 = [1,2,3]
key1 == key2 // false, which is weird

map = {}
map[key1] = 1
map[key2] = 2
map[key1] == map[key2] // true - wait, what?

Even though key1 and key2 are not equal to each other, they are equal as keys in an associative array.

This is because of the way objects are treated in javascript, especially when using objects as keys in associative arrays.

This is a crucial difference in equality of objects and can cause very subtle bugs if not understood properly.

Conclusion #

Objects in javascript can be used as keys in associative arrays, but it’s important to understand what the key really is and what it isn’t.



Now read this

GUI as an adjective

I’m lucky to currently be working in an office with no other programmers and only graphic designers. I’m used to working with other software developers, which I enjoy because we have a lot of crossover in our day-to-day work. But working... Continue →