Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript chained inequality gives bizarre results [duplicate]

Tags:

javascript

(0 <= 0 <= 0) === false
(-1 < 0 <= 0 <= 0) === true

What's going on here? Does Javascript actually have inequality chaining that's just wrong in some cases?

like image 668
Bryan Head Avatar asked Jun 11 '26 10:06

Bryan Head


2 Answers

Typed up the question and then was struck by the answer. Javascript does not have inequality chaining. Rather, 0 <= 0 <= 0 becomes true <= 0, which is evaluated as 1 <= 0. Indeed, 0 < 0 <= 0 evaluates to true.

like image 147
Bryan Head Avatar answered Jun 13 '26 23:06

Bryan Head


There is no chaining of operator but precedence. Here all the operators have the same priority so the operations are done from left to right.

When your comparison involves a boolean, the MDN explains how the comparison works :

If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.

This means the first operation is decomposed according to priorities as

((0 <= 0) <= 0)

which is

true <= false

which is

false

And the second one is

(true <= 0) <= 0

which is

false <= 0 

which is true.

like image 29
Denys Séguret Avatar answered Jun 13 '26 23:06

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!