Search code examples
javascriptcomparison-operators

Why does greater than behave like this in Javascript?


I'm looking at Comparison operators in Javascript and came across these examples:

console.log(1 < 2 < 3);

This equals true, which feels like it makes sense as 1 is less than, 2 and 2 is less than 3...

console.log(3 > 2 > 1);

However this equals false, which I don't understand...

Here's a jsFiddle to also show the behavior if you open up the web developer tools and look at the console.

Someone suggested, it had to do with precedence but reading about precedence at MDN, I can't find a explanation to this.

Can anyone explain in a resonable simple way, what is going on there?


Solution

  • In JavaScript, chaining of comparison operators won't work; it will first evaluate the first comparison to true/false, convert it into 1/0 and then do the second comparsion:

    1 < 2 < 3   =>   (1 < 2) < 3
                =>      true < 3
                =>         1 < 3
                =>          true    
    
    3 > 2 > 1   =>   (3 > 2) > 1
                =>      true > 1
                =>         1 > 1
                =>         false
    

    You should instead split it into two separate comparsions: 1 < 2 && 2 < 3.