0

I saw an exciting and confusing issue. Based on "JavaScript, the good parts" :

'' == '0'           // false
0 == ''             // true

So, why?!

Amir Jalilifard
  • 2,027
  • 5
  • 26
  • 38
  • 2
    tl;dr type coercion. http://stackoverflow.com/questions/19915688/what-exactly-is-type-coercion-in-javascript or http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons for more. – Dan Smith Feb 09 '15 at 16:47
  • 1
    https://www.destroyallsoftware.com/talks/wat – error Feb 09 '15 at 16:48
  • @Dom Interestingly, PHP considers `"0"` to be a falsy string, presumably because databases pass all values as strings and so a "false" value from a database needed to be considered falsy. Really, really hacky and annoying at times XD – Niet the Dark Absol Feb 09 '15 at 16:49
  • Not sure why it confuses you that comparing different values gives a different result. –  Feb 09 '15 at 16:57

2 Answers2

2

Simple answer: Because it is.

Advanced answer:

  • '' == '0' compares the items as strings, since they're both strings. No type changes needed, just compare. They're blatantly different, so false.

  • 0 == '' compares the items as numbers. '' converts to 0 so they are the same.

But really, who cares?

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

In the first case, both are of type String and hence do not equate, as they are compared by their values.

In the second case, the left hand side is a Number, so there is a conversion occurring, which makes '' to 0 and hence true

== results in typecasting and then comparing, if needed. === doesn't typecast, so

0 === '' // false
Amit Joki
  • 58,320
  • 7
  • 77
  • 95