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?
These examples were found by jimbojw http://jimbojw.com fame as well as walkingeyerobot.
It is because of the implicit type conversion of
==
operator.[2] is converted to Number is 2 when compared with a Number. Try the unary
+
operator on [2].That's interesting, it's not that [0] is both true and false, actually
It is javascript's funny way of processing if() operator.
You are comparing 2 objects in every case.. Dont use ==, if you are thinking of comparison, you are having === in mind and not ==. == can often give insane effects. Look for the good parts in the language :)