JavaScript gets a lot of criticism for its quirks, and this one appears in almost every “JS is weird” meme:

console.log(3 < 2 < 1); // true

It looks like a bug. It is not. The result follows from three well-defined rules, and once you know them the expression becomes predictable:

  1. Operators return values
  2. Operator precedence and associativity
  3. Type coercion

Operators return values

Comparison operators work much like functions. They take operands, do something with them and return a result:

console.log(1 < 2); // true

The < operator compares 1 and 2 and returns true.

The assignment operator works the same way. It assigns a value and also returns it:

let x;
console.log((x = 5)); // 5

This matters because the result of one operator can become the operand of the next one. That is exactly what happens in 3 < 2 < 1.

Precedence and associativity

When an expression contains several operators, JavaScript needs to know which one to evaluate first.

Precedence

Precedence decides which operator runs first when operators differ. Take:

x = 2 < 3;
  1. < has higher precedence than =, so it runs first.
  2. 2 < 3 evaluates to true.
  3. x = true assigns true to x.

Associativity

Associativity decides the order when operators have the same precedence. The relational operators <, >, <= and >= are left-associative, so they are evaluated from left to right. Consider:

console.log(1 < 2 < 3); // true
  1. 1 < 2 evaluates to true.
  2. Next, JavaScript evaluates true < 3.

Comparing a boolean with a number does not throw an error. JavaScript converts one of the values instead, which brings us to the last rule.

Type coercion

Type coercion is JavaScript’s implicit conversion of a value from one type to another. When a relational comparison involves a boolean and a number, the boolean is converted to a number:

console.log(Number(true)); // 1
console.log(Number(false)); // 0

So the second step of the previous example is:

true < 3; // becomes 1 < 3, which is true

That is why 1 < 2 < 3 returns true. It happens to match what we expect, but only by accident.

Putting it together: 3 < 2 < 1

console.log(3 < 2 < 1); // true
  1. 3 < 2 evaluates to false.
  2. The result is used in the next comparison: false < 1.
  3. false is coerced to 0.
  4. 0 < 1 evaluates to true.

The same rules explain the mirror case, which surprises people just as much:

console.log(3 > 2 > 1); // false, because true > 1 becomes 1 > 1

Takeaway

None of this is random. Precedence, associativity and type coercion fully explain the behaviour. The practical lesson is that chained comparisons do not mean in JavaScript what they mean in mathematics. If you want to check that a value sits in a range, write it explicitly:

const inRange = 1 < x && x < 3;

The next time you see a “JavaScript is weird” meme about this, you will know the language is doing exactly what its rules say it should.


Originally published on dev.to in December 2020. Lightly edited.