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.

Top

 
2
Kudos
 
2
Kudos

Now read this

Screen Brightness on a KiraBook with Ubuntu 14.04

The backlight on my new laptop was not working - a Toshiba KiraBook running Ubuntu 14.04. The buttons for screen brightness (F2 and F3) did not cause the brightness to change. Also, the OSD feedback incorrectly showed “Power Manager” for... Continue →