-2

Such code in JS 10 <= x <= 100 for any number x will always return true.

How is it called ? Why does it behave like this ? Where can I found some doc about it ?

Is 10 <= x && x <= 100 the shortest way to do things properly ?

SidoShiro92
  • 169
  • 2
  • 16
  • 2
    Because it's evaluated as `(10 <= x) <= 100`, so `(true/false) <= 100`, and both `true` and `false` are `<= 100`. – deceze May 10 '21 at 13:07
  • It behaves like that because the `<=` operator is left-associative, so it's parsed as `(10 <= x) <= 100`. That's `true` because `10 <= x` returns a boolean value, and it'll be converted to either 0 or 1 in the comparison to 100. The documentation is the description of JavaScript expressions in *any* book or online reference for the language. – Pointy May 10 '21 at 13:08
  • I think this question is much more general and applicable than the one it is marked a "duplicate" of this. (edit: I do agree somewhat with the duplicity... But not at all with the downvotes. It's a great question.) – Chris Wesseling May 10 '21 at 13:17
  • @SidoShiro92 If you want to study the subject more. Transitivity and associativity of (comparison) operators are the terms to search for. – Chris Wesseling May 10 '21 at 13:21
  • 1
    Unlike python JS doesn't evaluate `x < y < z` "mathematically". – georg May 10 '21 at 13:24
  • 1
    https://stackoverflow.com/questions/6454198/check-if-a-value-is-within-a-range-of-numbers – John Montgomery May 11 '21 at 18:36

1 Answers1

2

See Abstract Relational Comparison

10 <= x is going to be true or false.

Then someBoolean <= 100 is going to cause the boolean to be converted to a number 1 or 0.

Both 1 and 0 are less than 100.


If you want to do two comparisons of a number then you need to explicitly make two comparisons and combine them with &&, not by simply mashing them together.

10 <= x && x <= 100
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335