Question

i came from a python background and came across an issue after doing a javascript project where

0 < 5 < 3

outputs to true which my guess is that it runs the first operator and completely disregards the second

and python it will render to false.

im not concerned about how to get this to work but its odd that its not in the documentation its only implied to do (0 < x && x < 3 ) and not keep it simple

guess my question is why is this like this if anyone can even answer

Was it helpful?

Solution

In JavaScript, this:

0 < 5 < 3

is evaluated like this:

(0 < 5) < 3

which translates to this:

true < 3

which is further translated to this (because true is 1 in a numerical context):

1 < 3

which is true.


Python however was designed differently. As documented here, it interprets this:

0 < 5 < 3

as being equivalent to this:

0 < 5 and 5 < 3

The above expression can be further translated to this:

True and False

which is false.

OTHER TIPS

Here is a step by step evaluation. When comparing a number and a boolean with <, true becomes 1, and 0 becomes false.

0 < 5 < 3 // =>
true < 3 // =>
Number(true) < 3 // =>
1 < 3 // =>
true

See spec 11.8.5, rule 3, which describes the ToNumber casting.

3) If it is not the case that both Type(px) is String and Type(py) is String, then

a) Let nx be the result of calling ToNumber(px). Because px and py are primitive values evaluation order is not important.

b) Let ny be the result of calling ToNumber(py).

In JavaScript, Relational operators are executed from left to right:

0 < 5

would be true, i.e. 1, so

0 < 5 < 3

translates into:

1 < 3

which is true.

On the other hand, comparison operations in Python have the same priority.

Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top