Skip to main content

Command Palette

Search for a command to run...

Why 3 > 2 > 1 gives false

Updated
2 min read
Why 3 > 2 > 1 gives false
K

Thanks to some friends, I started programming in high school with QBASIC. Nowadays, I'm a software engineer working mostly in Java and active on Exercism. On weekends, you can find me outside, at a parkrun, tending to the veggie patch or the six backyard chooks.

Recently, I saw this question about how does Javascript evaluate an expression:

So, why does 1 < 2 < 3 give true, but 3 > 2 > 1 give false? According to operator precedence and associativity, they are evaluated from left to right. So...

  1. 1 < 2 < 3 is evaluated as (1 < 2) < 3.
  2. 1 < 2 is true, making the expression true < 3.
  3. How does it compare a true against a number? It does this by first converting the boolean to a number. true is converted to 1 and false is converted to 0 (see 7.1.14 of the ECMAScript specififcation). Thus, the expression is evaluated as 1 < 3 which gives true.

Now for 3 > 2 > 1:

  1. Going left to right, 3 > 2 is evaluated first which is true. The expression becomes true > 1.
  2. To evaluate, true is converted to 1. This gives 1 > 1, which is false!

For bonus points, try figuring out 1 < 3 > 2 and 1 > 3 < 2 gives.

(originally posted on Dev.to)

93 views
M
Mark5y ago

Useful warning to prevent this pitfall!

Some languages like Python understand this syntax (so that 1 < 2 < 3 is the same as 1 < 2 and 2 < 3). Many others give an error. I think Javascript's behaviour is an unfortunate mistake.

More from this blog

Kah Goes Coding

10 posts

Thanks to some friends, I started learning to program in high school. Now I am a software engineer. I can sometimes be found running, tending to my garden or playing with my six backyard chooks.