Search code examples
javascriptcomparison

Why 5<4<2 is returning true?


I am practicing Javascript. I came across one scenario where I am comparing 3 numbers as below:

console.log(5<4<2);

It returns true. Now that I don't understand why. By operator precendence it must evaluate left to right which means false<2. Is something strange done by js in this case?


Solution

  • This is because of the Operator precedence.

    Less than (<) operator is evaluated from left-to-right.

    First 5<4 is evaluated to false then false is converted to 0 in the next evaluation. Finally 0<2 is evaluated to true

    console.log(5<4);// false
    console.log(0<2);// true