Skip to content

Chained comparisons

Baseline logo Baseline
Chrome logo Edge logo
Firefox logo Zen logo
Safari logo
Node logo
Bun logo
Deno logo
Cloudflare Workers logo

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
JS+ TypeScript
const one = 1;
const two = 2;
const three = 3;
one == two == three; // false
one != two != three; // true
one === two === three; // false
one !== two !== three; // true
one < two < three; // true
one <= two <= three; // true
one > two > three; // false
one >= two >= three; // false
const one = 1;
const two = 2;
const three = 3;
one == two && two == three; // false
one != two && two != three; // true
one === two && two === three; // false
one !== two && two !== three; // true
one < two && two < three; // true
one <= two && two <= three; // true
one > two && two > three; // false
one >= two && two >= three; // false

With expressions

JS+ TypeScript
const arr = [0, 1, 2, 3];
arr[0] == arr[1] == arr[2]; // false
arr[0] != arr[1] != arr[2]; // true
arr[0] === arr[1] === arr[2]; // false
arr[0] !== arr[1] !== arr[2]; // true
arr[0] < arr[1] < arr[2]; // true
arr[0] <= arr[1] <= arr[2]; // true
arr[0] > arr[1] > arr[2]; // false
arr[0] >= arr[1] >= arr[2]; // false
const arr = [0, 1, 2, 3];
arr[0] == arr[1] && arr[1] == arr[2]; // false
arr[0] != arr[1] && arr[1] != arr[2]; // true
arr[0] === arr[1] && arr[1] === arr[2]; // false
arr[0] !== arr[1] && arr[1] !== arr[2]; // true
arr[0] < arr[1] && arr[1] < arr[2]; // true
arr[0] <= arr[1] && arr[1] <= arr[2]; // true
arr[0] > arr[1] && arr[1] > arr[2]; // false
arr[0] >= arr[1] && arr[1] >= arr[2]; // false

You can also chain more than 3 operators and different operators together:

JS+ TypeScript
const a = 1;
const b = 2;
const c = 3;
a == b < c <= b; // false
a >= b !== c; // false
const a = 1;
const b = 2;
const c = 3;
a == b && b < c && c <= b; // false
a >= b && b !== c; // false

This syntax already exists in 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); // true

Since 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; // true
true < three; // it's still true because true is coerced into 1 and 1 < 3 is true

But obviously 10 is not between 1 and 3.

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)
}