Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript chained relational operators supported?

Tags:

javascript

I just played around with some JS core principles and found, that the engine evaluates chained relational operators without throwing an error. Instead they are evaluated in a way I can't understand for myself.

console.log(1 < 2 < 3 < 4 < 5); //true, expected
console.log(5 > 4 > 3 > 2 > 1); //false, should be true
console.log(5 >= 4 >= 3);       //false, should be true
console.log(7 >= -2 >= 1);      //true, should be false
console.log(1 <= -2 <= 7);      //true, should be false

Is this even officially supported? I also found no mentions in literature / documentations on this and I am rather confused why this is even working.

Somebody can light this up a bit?

like image 638
Jankapunkt Avatar asked Dec 23 '22 07:12

Jankapunkt


2 Answers

They're binary operators, with left associativity. They're parsed as

console.log((((1 < 2) < 3) < 4) < 5); // true (true < 5)
console.log((((5 > 4) > 3) > 2) > 1); // false (true > 1)
console.log((5 >= 4) >= 3);           // false (true >= 3)
console.log((7 >= -2) >= 1);          // true (true >= 1)
console.log((1 <= -2) <= 7);          // true (false <= 7)

and will compare boolean partial results with numbers.

like image 143
Bergi Avatar answered Jan 12 '23 07:01

Bergi


1 < 2 evaluates to true

true < 3 evaluates to true

true < 4 evaluates to true

true < 5 evaluates to true


5 > 4 evaluates to true

true > 3 evaluates to false

false > 2 evaluates to false

false > 1 evaluates to false


The reason for this logic is that true and false are treated as 1 and 0 respectively for these sorts of comparisons.

like image 37
zzzzBov Avatar answered Jan 12 '23 07:01

zzzzBov