Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use chained comparison operator syntax? [duplicate]

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?

like image 957
Sergey Metlov Avatar asked Dec 13 '22 10:12

Sergey Metlov


1 Answers

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.

like image 83
user113716 Avatar answered Dec 28 '22 11:12

user113716