user2045806
user2045806

Reputation:

Javascript comparisons

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.

Upvotes: 0

Views: 61

Answers (3)

six fingered man
six fingered man

Reputation: 2500

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

Upvotes: 3

Yoann Augen
Yoann Augen

Reputation: 2036

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

Upvotes: 0

Hobbes
Hobbes

Reputation: 801

I think this is because it is parsed as such:

( (0 == false) == 0 )

Which would be saying

( true == false )

Upvotes: 0

Related Questions