Alex Rivera | Logout

Why does 2 == [2] in JavaScript?

Asked 2009-11-12T18:10:17.640
172

I recently discovered that 2 == [2] in JavaScript. As it turns out, this quirk has a couple of interesting consequences:

var a = [0, 1, 2, 3];
a[[2]] === a[2]; // this is true

Similarly, the following works:

var a = { "abc" : 1 };
a[["abc"]] === a["abc"]; // this is also true

Even stranger still, this works as well:

[[[[[[[2]]]]]]] == 2; // this is true too! WTF?

These behaviors seem consistent across all browsers.

Any idea why this is a language feature?

Here are more insane consequences of this "feature":

[0] == false // true
if ([0]) { /* executes */ } // [0] is both true and false!

var a = [0];
a == a // true
a == !a // also true, WTF?
Edit
Report

2 Answers

8

For the == case, this is why Doug Crockford recommends always using ===. It doesn't do any implicit type conversion.

For the examples with ===, the implicit type conversion is done before the equality operator is called.

answered 2009-11-12T18:21:11.037
7

A array of one item can be treated as the item itself.

This is due to duck typing. Since "2" == 2 == [2] and possibly more.

answered 2009-11-12T18:13:59.820

Your Answer