0

I would like to know why the following comparisons in javascript will give me different results.

(1==true==1)
true

(2==true==2)
false

(0==false==0)
false

(0==false)
true

I can not figure out why.

  • 6
    I'm wondering how you ended up with those lines of code – The_Black_Smurf Dec 01 '14 at 22:00
  • Related: [Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?](http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons) and [Implicit data type conversion in JavaScript when comparing integer with string using ==](http://stackoverflow.com/questions/7625144/implicit-data-type-conversion-in-javascript-when-comparing-integer-with-string-u) – Jonathan Lonowski Dec 01 '14 at 22:06
  • @JonathanLonowski Thanks, I will read. –  Dec 01 '14 at 22:06
  • http://stackoverflow.com/questions/7615214/in-javascript-why-is-0-equal-to-false-but-not-false-by-itself – epascarello Dec 01 '14 at 22:11

3 Answers3

3

The tests are equivalent to these:

(true==1)
true

(false==2)
false

(true==0)
false

which is equivalent to these:

(1==1)
true

(0==2)
false

(1==0)
false

In each case the == converts the boolean to a number 1 or 0. So the first == in each one gives the initial true/false value, which is then used as the first operand for the second ==.


Or to put it all inline:

((1==true)==1)
((1==1)   ==1)
((true)   ==1)
((1)      ==1)
true

((2==true)==2)
((2==1)   ==2)
((false)  ==2)
((0)      ==2)
false

((0==false)==0)
((0==0)    ==0)
((false)   ==0)
((0)       ==0)
false
six fingered man
  • 2,460
  • 12
  • 15
  • Why (2==true) is false? –  Dec 01 '14 at 22:02
  • I am almost understanding. Why (2) is true and (2==true) is false? –  Dec 01 '14 at 22:04
  • Because it is true that 2 exists as a value, but is false that 2 == true =] – Hobbes Dec 01 '14 at 22:05
  • @user2045806: Because (2) is a simple "truthy" evaluation, so any non-zero (or non-NaN) number is considered `true`, but the `==` is doing type coercion, where `true` becomes the number `1` and the number `2` is not equal to the number `1`. – six fingered man Dec 01 '14 at 22:06
0

I think this is because it is parsed as such:

( (0 == false) == 0 )

Which would be saying

( true == false )
Hobbes
  • 781
  • 10
  • 29
0

Each of this operation is done in two steps.

(1==true==1)

first operation is 1 == true => true

So second is true == 1 => true

(2==true==2)

first operation is 2 == true => false (just number 1 is equivalent to true in js)

So second is false == 2 => true

(0==false==0)

first operation is 0 == false => true

So second is true == 0 => false

Yoann Augen
  • 1,966
  • 3
  • 21
  • 39