Chained comparisons
Chained comparisons let you concatenate multiple comparisons into a single expression without the need of the && gate.
| Type | TC39 | CoreJS | Babel | Civet | JS+ |
|---|---|---|---|---|---|
| Runtime | ❌ | ❌ | ✅ View | ✅ via Custom |
const one = 1;const two = 2;const three = 3;
one == two == three; // falseone != two != three; // true
one === two === three; // falseone !== two !== three; // true
one < two < three; // trueone <= two <= three; // true
one > two > three; // falseone >= two >= three; // falseconst one = 1;const two = 2;const three = 3;
one == two && two == three; // falseone != two && two != three; // true
one === two && two === three; // falseone !== two && two !== three; // true
one < two && two < three; // trueone <= two && two <= three; // true
one > two && two > three; // falseone >= two && two >= three; // falseWith expressions
const arr = [0, 1, 2, 3];
arr[0] == arr[1] == arr[2]; // falsearr[0] != arr[1] != arr[2]; // true
arr[0] === arr[1] === arr[2]; // falsearr[0] !== arr[1] !== arr[2]; // true
arr[0] < arr[1] < arr[2]; // truearr[0] <= arr[1] <= arr[2]; // true
arr[0] > arr[1] > arr[2]; // falsearr[0] >= arr[1] >= arr[2]; // falseconst arr = [0, 1, 2, 3];
arr[0] == arr[1] && arr[1] == arr[2]; // falsearr[0] != arr[1] && arr[1] != arr[2]; // true
arr[0] === arr[1] && arr[1] === arr[2]; // falsearr[0] !== arr[1] && arr[1] !== arr[2]; // true
arr[0] < arr[1] && arr[1] < arr[2]; // truearr[0] <= arr[1] && arr[1] <= arr[2]; // true
arr[0] > arr[1] && arr[1] > arr[2]; // falsearr[0] >= arr[1] && arr[1] >= arr[2]; // falseYou can also chain more than 3 operators and different operators together:
const a = 1;const b = 2;const c = 3;
a == b < c <= b; // falsea >= b !== c; // falseconst a = 1;const b = 2;const c = 3;
a == b && b < c && c <= b; // falsea >= b && b !== c; // falseSupport
Section titled “Support”This syntax already exists in JavaScript
JavaScript
Section titled “JavaScript”Technically, chained comparison can be parsed by JavaScript, but it wouldn’t work as expected.
const one = 1;const ten = 10;const three = 3;
console.log(one < ten < three); // trueSince in a chained comparison expression, all the operators have the same precedence, JavaScript will parse the expression from left to right. The operators ==, !=, ===, !==, <, <=, > and >= are binary operators, so they evaluate the comparison only between two values at a time. JavaScript will parse the expression like this (one < ten) < three
const one = 1;const ten = 10;const three = 3;
one < ten; // truetrue < three; // it's still true because true is coerced into 1 and 1 < 3 is trueBut obviously 10 is not between 1 and 3.
TypeScript
Section titled “TypeScript”TypeScript will throw a type error if you try to chain comparisons:
if (1 < 10 < 3) { //~~~~~~~~~~ • Operator '<' cannot be applied to types 'boolean' and 'number'. ts(2365)}