You can look up the comparison algorithm in the ECMA-spec (relevant sections of ECMA-262, 3rd edition for your problem: 11.9.3, 9.1, 8.6.2.6).
If you translate the involved abstract algorithms back to JS, what happens when evaluating 2 == [2]
is basically this:
2 === Number([2].valueOf().toString())
where valueOf()
for arrays returns the array itself and the string-representation of a one-element array is the string representation of the single element.
This also explains the third example as [[[[[[[2]]]]]]].toString()
is still just the string 2
.
As you can see, there’s quite a lot of behind-the-scene magic involved, which is why I generally only use the strict equality operator ===
.
The first and second example are easier to follow as property names are always strings, so
a[[2]]
is equivalent to
a[[2].toString()]
which is just
a["2"]
Keep in mind that even numeric keys are treated as property names (ie strings) before any array-magic happens.