Why does 3>2>1
return false
while 1 < 2 < 3
returns true
?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
Why does 3>2>1
return false
while 1 < 2 < 3
returns true
?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
Since 1 < 2
evaluates to true
and 3 > 2
evaluates to true
, you're basically doing :
console.log(true < 3);
console.log(true > 1);
And true
is converted to 1
, hence the results.
Because it interprets left to right and because it tries to cast to same type.
1 < 2 < 3
becomes true < 3
, which because we are comparing numbers is cast to 1 < 3
which is truth.
3 > 2 > 1
becomes true > 1
, which because we are comparing numbers is cast to 1 > 1
which is false.
That is because it is evaluated from left to right, making it equivalent to the below commands:
console.log(true < 3);
console.log(true > 1);
Operator "<" and ">" Associativity is left-to-right so
Check below link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
console.log(1 < 2 < 3) ==> console.log(true < 3)==> (true means 1)=> console.log(1 < 3); Answer is true
console.log(3 > 2 > 1) ==> console.log(true >1)==> (true means 1)=> console.log(1 >1); Answer is false
console.log(3 > 2 >=1) ==> console.log(true >=1)==> (true means 1)=> console.log(1 = 1); Answer is true
Compiler will read like this
$console.log((1 < 2) < 3)
and $ console.log(( 3>2 ) > 1)
in 1st case: $ console.log(1 < 2 < 3)
first compiler execute 1<2 which returns 1(true), after that it goes like 1<3 which is again 1(true). hence overall it is true.
execute 2nd one with same logic, it will gives you false.