Open a console window and type
1 < 2 < 3
and the output will be true
.
So far so good, lets try another example. Now type
3 > 2 > 1
we get false
. whoops!
Turns out 1 < 2 < 3
returning true was a complete accident and something else was going behind the scenes.
Evaluating a comparision expression
To understand whats going on,lets understand how a comparision is evaluated
Here is the link if someone wants to go through the spec. 262.ecma-international.org/12.0/#sec-abstra..
While evaluating a comparision operation, say x > y, both x and y are first coerced to numeric values
For example
let x = 3, y = 2;
x > y //outputs true
in the above block since both x and y are already numeric, they are returned as it is and a numerical comparision takes place
The Answer
Now that we have a basic idea of how a comparision expression is evaluated, lets get back to our earlier code
let x = 3, y = 2, z = 1
3 > 2 > 1
// this is evaluated left to right so, the expression is evaluated as
(3 > 2) > 1
//which becomes
true > 1
Since the comparision is broken down into two operations, the result of first operation is compared to the right most operand, which in our case becomes,
true > 1
// first coerce true to a numeric value
+true //outputs 1
//the expression after coercion becomes
1 > 1 // finally outputs false
Thanks for reading!