Search code examples
javascriptoperatorscomparison-operators

Can I use chained comparison operator syntax?


In one JS library I saw such syntax:

if (val > 5 == t) { ... }

I tested this in console:

1 == 1 == 2 // false
2 > 1 == 1  // true
1 == 2 == 1 // false
1 == 1 == 1 // true
1 < 2 < 3   // true
1 > 2 > 3   // false

At first glance all correct. Can this be used?


Solution

  • 1 == 1 == 2  // this
    true == 2    // becomes this
    1 == 2       // which becomes this, and is false
    
    2 > 1 == 1  // this
    true == 1   // becomes this
    1 == 1      // which becomes this, and is true
    

    ...and so on.

    If you're wondering about the conversion, you should do a search on the == operator, which uses the Abstract Equality Comparison Algorithm.