0

I just found out, that I can not chain "less than" operators in JavaScript. I wonder if anyone know why?

Example:

console.log ("should be false but is", (0 < 3 < 2)) // true

I can't find any documentation that says that, this expression will short-circuit after the first comparison (0 < 3). So why is the last comparison not made?

I have tested the expression in nodejs 16 (V8) and Firefox 111 (SpiderMonkey).

dotnetCarpenter
  • 10,019
  • 6
  • 32
  • 54
  • 3
    What short-circuiting do you expect here? It's parsed as `(0 < 3) < 2`, so `true < 2`, thn `1 < 2` and it's `true` - why do you expect `false` here? There is no operator chaining like in python. – STerliakov Feb 26 '23 at 13:19
  • 4
    It's not shortcircuiting, `0 < 3` results `true` that is evaluated to `1`, and that is compared to `2`. – Teemu Feb 26 '23 at 13:19
  • Ahh ok I see. I expected `3 < 2` but got `1 < 2`. – dotnetCarpenter Feb 26 '23 at 13:21
  • 3
    Python is really the odd-one-out in this respect. Most programming languages either don't allow this syntax, or first evaluate `0 < 3` to a boolean and then evaluate `(boolean) < 2`, which (after coercion of the boolean to an integer) will result in true, no matter what the boolean result was. – trincot Feb 26 '23 at 13:21
  • I'll accept any of the comments as answer - if you want the points :) – dotnetCarpenter Feb 26 '23 at 13:24

0 Answers0