Sub topic 12
Relational Comparisons and Their Surprises
The relational operators <, >, <= and >= look simple. Their conversion rules differ from both === and ==, though, so the results can surprise you. This chapter shows the algorithm behind these operators and explains why null >= 0 is true while null == 0 is false. It also covers how to compare strings, dates and mixed types reliably.
This chapter assumes you already know the coercion steps ToPrimitive, ToNumber and ToString, the loose equality rules, and how NaN behaves. Those topics have their own earlier chapters.
The Four Operators at a Glance
Each relational operator returns a boolean. None of them has a "strict" version: there is no <==. Relational comparison always converts its operands when their types differ.
console.log('10' < '9'); // true: string comparison by code unit
console.log(10 < '9'); // false: '9' is converted to a number
console.log(null >= 0); // true: null becomes 0
console.log(null > 0); // false
console.log(null == 0); // false: == has a special rule for null
console.log(undefined < 1); // false: undefined becomes NaNYou can explain each line once you know the algorithm.
How the Comparison Algorithm Works
The specification defines one core operation, IsLessThan(x, y). All four operators are built on it.
- Convert both operands with ToPrimitive using the hint
"number". For objects, this meansvalueOfis tried beforetoString. The left operand is converted first. - If both primitives are strings, compare them code unit by code unit. No numeric conversion happens.
- If one side is a BigInt and the other is a string, parse the string as a BigInt. If the parse fails, the result is "undefined".
- Otherwise, convert both sides with ToNumeric. If either side is NaN, the result is "undefined". If not, compare the numbers mathematically.
The "undefined" result is internal. It never reaches your code directly, but it matters for how the operators are derived:
| Expression | Defined as | When IsLessThan gives undefined |
|---|---|---|
| `a < b` | IsLessThan(a, b) | `false` |
| `a > b` | IsLessThan(b, a) | `false` |
| `a <= b` | not IsLessThan(b, a) | `false` |
| `a >= b` | not IsLessThan(a, b) | `false` |
The important detail is that <= does not mean "less than or equal". It means "not greater than". JavaScript never checks equality inside <=. That difference explains several of the surprises below.
Surprise 1: null, undefined and the Missing Equality Check
The == operator has a special rule: null equals only null and undefined. Relational operators have no such rule. They simply apply ToNumber, which turns null into 0 and undefined into NaN.
console.log(null < 1); // true: 0 < 1
console.log(null > 0); // false: 0 > 0 is false
console.log(null >= 0); // true: "not (null < 0)" is "not false"
console.log(null == 0); // false: == never converts null to a number
console.log(undefined <= undefined); // false: NaN makes the result undefined
console.log(NaN <= NaN); // false
console.log(NaN >= NaN); // falseSo null >= 0 is true, null > 0 is false, and null == 0 is false. The three results disagree because two different algorithms produce them.
Surprise 2: Strings Compare by Code Unit
When both operands are strings, JavaScript compares their UTF-16 code units from left to right. At the first position where the strings differ, the string with the lower code unit is smaller. If one string is a prefix of the other, the shorter string is smaller.
console.log('apple' < 'apples'); // true: prefix is smaller
console.log('abc' < 'abd'); // true: 'c' (99) < 'd' (100)
console.log('Z' < 'a'); // true: 'Z' is 90, 'a' is 97
console.log('a' < 'B'); // false: 97 is not less than 66
console.log('é' > 'z'); // true: U+00E9 is above U+007A
console.log('10' < '9'); // true: '1' (49) < '9' (57)This ordering is fine for checking whether two identifiers sort consistently. It is wrong for anything a person reads, such as names, accented words or file names containing numbers. For those, use locale-aware collation:
const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' });
console.log(collator.compare('10', '9')); // 1: numeric option treats digits as numbers
console.log(collator.compare('a', 'B')); // -1: case does not dominate the order
console.log('é'.localeCompare('z', 'en')); // -1: é sorts near e
const files = ['file10.txt', 'file9.txt', 'File1.txt'];
console.log(files.sort(collator.compare)); // [ 'File1.txt', 'file9.txt', 'file10.txt' ]Surprise 3: Mixed Types Become Numbers
If only one side is a string, both sides become numbers. Whitespace-only and empty strings become 0. Unparseable strings become NaN, and a NaN makes every comparison false.
console.log(10 < '9'); // false: 10 < 9
console.log('' < 1); // true: '' becomes 0
console.log(' ' < 1); // true: whitespace becomes 0
console.log('abc' < 1); // false: NaN
console.log('abc' >= 1); // false: also NaN, so both directions fail
console.log(true > false); // true: 1 > 0The last pair of 'abc' lines shows a useful rule. If both a < b and a >= b are false, at least one operand converted to NaN.
Surprise 4: Objects, Arrays and Dates
Objects go through ToPrimitive with the number hint first. Arrays have no useful valueOf, so they fall back to toString. Dates return their timestamp from valueOf, so comparing dates works.
console.log([2] > 1); // true: [2] -> '2' -> 2
console.log([1, 2] < 3); // false: '1,2' -> NaN
console.log({} < {}); // false: '[object Object]' vs itself
console.log({} <= {}); // true: "not greater than" is satisfied
const price = { valueOf() { return 42; } };
console.log(price > 40); // true: valueOf supplies 42
const d1 = new Date('2026-01-01');
const d2 = new Date('2026-01-01');
console.log(d1 <= d2 && d1 >= d2); // true: same timestamp
console.log(d1 == d2); // false: different objects
console.log(d1.getTime() === d2.getTime()); // true: compare the numbersThe date example combines two rules. Relational operators convert the objects to their timestamps. Equality operators compare the object references. As a result, two dates can be both <= and >= each other and still not be ==. To test whether two dates are equal, compare getTime() values.
Surprise 5: Default Sorting Uses Strings
Array.prototype.sort does not use < on numbers. Without a comparator, it converts the elements to strings and sorts them by code unit.
console.log([10, 9, 1, 100].sort()); // [ 1, 10, 100, 9 ]
console.log([10, 9, 1, 100].sort((a, b) => a - b)); // [ 1, 9, 10, 100 ]Always pass a comparator when you sort numbers. When you sort strings for display, pass Intl.Collator or localeCompare.
BigInt in Relational Comparisons
BigInt values compare with Numbers by their mathematical value, so no precision is lost. A string compared with a BigInt must parse as an integer. Otherwise the comparison is false.
console.log(1n < 2); // true
console.log(2n > 1.5); // true: exact mathematical comparison
console.log(1n < '2'); // true: '2' parses as 2n
console.log(1n < '1.5'); // false: '1.5' is not a valid BigInt
console.log(1n >= '1.5'); // false: same failed parseChoosing a Safe Comparison
| Situation | Recommended approach |
|---|---|
| Numbers you have validated | `<`, `>`, `<=`, `>=` directly |
| Input that may be a string | Convert with `Number()` and check `Number.isNaN` first |
| Possibly null or undefined | Check for nullish values before comparing |
| Human-readable strings | `Intl.Collator` or `localeCompare` |
| Dates | Relational operators for order, `getTime()` with `===` for equality |
| Sorting numbers | `sort((a, b) => a - b)` |
Exercise
Predict the output of each line and explain why: null <= 0, undefined >= 0, 'b' > 'a10', [10] < [9].
Show answer
null <= 0 is true because it means "not (0 < null)", and 0 < 0 is false. undefined >= 0 is false because undefined becomes NaN, which makes the comparison undefined, and every operator turns that into false. 'b' > 'a10' is true because both are strings and 'b' (98) is greater than 'a' (97) at the first position. [10] < [9] is true because both arrays become the strings '10' and '9', which compare by code unit, and '1' is less than '9'.
Exercise
Write a function isAtLeast(value, min) that returns true only when value is a finite number greater than or equal to min. Calling it with null, '' or '5' should return false.
Show answer
function isAtLeast(value, min) { return typeof value === 'number' && Number.isFinite(value) && value >= min; } The type check rejects null, empty strings and numeric strings before >= can convert them to numbers.
Exercise
Two Date objects a and b give a <= b and a >= b both true, but a == b is false. Explain why, and show how to test that they represent the same moment.
Show answer
Relational operators call ToPrimitive with the number hint, which uses each Date's valueOf timestamp, and the timestamps are equal. The == operator with two objects compares references, and these are different objects. Use a.getTime() === b.getTime() to test whether they represent the same moment.