javascriptboolean

1<2<3 is true but reverse of this 3>2>1 is false, why?


I am new in programming and learning web development, when I was doing practice of Boolean data type in javascript I got a problem with this:

Code: " console.log(1<2<3); console.log(3>2>1); "

Output: true false

I know the answer for the first one is true, but for second one why it printed false.


Solution

  • The difference between console.log(1 < 2 < 3); and console.log(3 > 2 > 1); lies in how JavaScript handles the comparison operators.

    Let's break down each expression:

    console.log(1 < 2 < 3);

    In this case, the expression is evaluated from left to right. 1 < 2 is true, so it becomes true < 3. JavaScript converts true to 1 in a numeric context, so it becomes 1 < 3. The final result is true. console.log(3 > 2 > 1);

    Similar to the first example, this expression is also evaluated from left to right. 3 > 2 is true, so it becomes true > 1. JavaScript converts true to 1 in a numeric context, so it becomes 1 > 1. The final result is false. The reason for the difference in behavior is that the < and > operators are left-associative in JavaScript, meaning they are evaluated from left to right. So, in the second example, it first evaluates 3 > 2, which is true, and then compares true > 1, which is false.

    console.log((1 < 2) < 3);  // true
    console.log(3 > (2 > 1));  // true
    
    

    Try this