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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With