skip to Main Content

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.

2

Answers


  1. First, it evaluates "3 > 2," which is true.
    Then, it evaluates "true > 1," treating "true" as 1 in a numerical context, which is false.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search