2

I was playing around with Chrome's Javascript console recently, and I discovered this oddity:

[] == true
false
[0] == true
false
[0] == []
false

This doesn't seem to make any sense at first glance (false != false), but I think the real reasoning lies in the polymorphism of the == operator. Comparing an array to a boolean isn't the same thing as comparing an array to another array.

With that said, what are other Javascript quirks you've discovered?

Zach Rattner
  • 19,821
  • 9
  • 55
  • 82
  • Haha, of course there's a whole site dedicated to making fun of Javascript. – Zach Rattner Apr 01 '11 at 00:56
  • 1
    Try with `===` and see what happens. – drudge Apr 01 '11 at 00:56
  • Open-ended list questions should be avoided, as per the faq: http://stackoverflow.com/faq#dontask – Yi Jiang Apr 01 '11 at 01:06
  • [The Garden](http://bonsaiden.github.com/JavaScript-Garden/). It's about quirks. – Raynos Apr 01 '11 at 01:08
  • In JavaScript, booleans are compared by value and arrays are compared by reference. So while `[0] == true` is false, `[0] == false` is true, and `[1] == true` is true. JavaScript is calling `valueOf()` on the array objects. – Paul Apr 01 '11 at 01:09

2 Answers2

3

I asked a similar question on equality transitivity recently and Alex provided a really good answer...

Alex's answer

I hope that helps.
Hristo

Community
  • 1
  • 1
Hristo
  • 44,041
  • 64
  • 159
  • 226
2

Look into truthy and falsey javascript. It's seriously called that.

Justin Thomas
  • 5,419
  • 3
  • 37
  • 60