The below javascript function outputs as false
, why is it resulted in false ?
console.log(15 > 10 > 5);
The below javascript function outputs as false
, why is it resulted in false ?
console.log(15 > 10 > 5);
Because comparison operators takes two operands. So first, your code evaluates 15 > 10
which returns true
and so then it does true > 5
which obviously returns false
The comparison operators take two operands and associates from left to right. This means the expression 15 > 10 > 5
is evaluated as (15 > 10) > 5
.
15 > 10
obviously evaluates to true
.
true > 5
is not that obvious how it is evaluated.
Fortunately, the JavaScript documentation explains how the values are converted when they have different types:
If one of the operands is Boolean, the Boolean operand is converted to
1
if it is true and+0
if it isfalse
.
This means true > 5
is evaluated the same way as 1 > 5
and only now the result is clear: it is false
.