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:
- First,
5 < xevaluates totrue(because 7 is greater than 5) - Then JavaScript evaluates
true < 10 - The boolean
truegets coerced to the number1 - Finally,
1 < 10evaluates totrue
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.