Recently, I saw this question about how does Javascript evaluate an expression:
gwagsi glenn@gwagsig
why is
console.log(1<2<3) ;
true
and
console.log(3>2>1) ;
fasle
?
#100DaysOfCode #CodeNewbies #javascript08:58 AM - 10 Sep 2020
So, why does 1 < 2 < 3 give true, but 3 > 2 > 1 give false? According to operator precedence and associativity, they are evaluated from left to right. So...
-
1 < 2 < 3is evaluated as(1 < 2) < 3. -
1 < 2istrue, making the expressiontrue < 3. - How does it compare a
trueagainst a number? It does this by first converting the boolean to a number.trueis converted to1andfalseis converted to0(see 7.1.14 of the ECMAScript specififcation). Thus, the expression is evaluated as1 < 3which givestrue.
Now for 3 > 2 > 1:
- Going left to right,
3 > 2is evaluated first which istrue. The expression becomestrue > 1. - To evaluate,
trueis converted to1. This gives1 > 1, which isfalse!
For bonus points, try figuring out For 1 < 3 > 2 and 1 > 3 < 2 gives.
Answers:
For 1 < 3 > 2:
1 < 3 is true, so it becomes true > 2.true is converted to 1, so it becomes 1 > 2, which is false.1 > 3 < 2:
1 > 3 is false, so it becomes false < 2.false is converted to 0, so it becomes 0 < 2, which is true.
Top comments (0)