Course contentsShow
← JavaScript
Lesson 213 of 2,7236. Booleans and ConditionalsFree lesson

Chaining Comparisons

Understand why comparison chaining (a < b < c) doesn't work as expected and alternatives.

Chaining Comparisons

You'll learn why writing a < b < c in JavaScript doesn't work the way you might expect—and what to do instead.


In many mathematical contexts, you can write something like "5 < x < 10" to mean "x is between 5 and 10." It's tempting to try this in JavaScript:

let x = 7;
let result = 5 < x < 10; // Looks like it should check if x is between 5 and 10
console.log(result); // true — but for the wrong reason!

Why It Doesn't Work

JavaScript evaluates comparisons left to right. Here's what actually happens:

  1. First, 5 < x evaluates to true (because 7 is greater than 5)
  2. Then JavaScript evaluates true < 10
  3. The boolean true gets coerced to the number 1
  4. Finally, 1 < 10 evaluates to true

This gives you the "right" answer by accident! But watch what happens with a different value:

let y = 50;
let result = 5 < y < 10; // y is NOT between 5 and 10
console.log(result); // true — WRONG!

Since 5 < 50 is true, and true (1) < 10 is also true, you get an incorrect result.

The Correct Alternative

Use logical AND (&&) to combine two separate comparisons:

let x = 7;
let result = 5 < x && x < 10; // Properly checks both conditions
console.log(result); // true

let y = 50;
let otherResult = 5 < y && y < 10; // Now correctly checks both
console.log(otherResult); // false

Key Takeaway: Comparison chaining like a < b < c doesn't work in JavaScript due to left-to-right evaluation and boolean-to-number coercion. Always use && to combine separate comparisons: a < b && b < c.