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.
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.
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
 
    
    I think this is because it is parsed as such:
( (0 == false) == 0 )
Which would be saying
( true == false )
 
    
    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
