Sub topic 2
Taking Control with Comparator Functions
The previous chapter showed that sort() with no arguments converts every element to a string and orders the results by UTF-16 code units. This chapter covers the fix: passing a comparator function that tells sort() how two elements relate. You will learn the contract a comparator must follow, how to write correct comparators for numbers, strings, dates, and objects, and which mistakes cause wrong results without throwing any error.
This chapter assumes you are comfortable with arrow functions, object property access, and the default sort() behavior covered in the previous chapter.
The Comparator Contract
A comparator is a function (a, b) => number. The sort algorithm calls it many times with pairs of elements and reads only the sign of the result:
| Return value | Meaning | Effect on order |
|---|---|---|
| Negative (e.g. `-1`, `-42`) | `a` comes before `b` | `a` placed first |
| Positive (e.g. `1`, `7.5`) | `a` comes after `b` | `b` placed first |
| Zero | `a` and `b` are equivalent | Relative order kept (sort is stable) |
The size of the number does not matter. -1 and -1000 mean the same thing. Two more rules come from the specification:
- The result goes through
ToNumber. ANaNresult is treated as0. undefinedelements never reach the comparator. They are always moved to the end, followed by any empty slots (holes) in sparse arrays.
Consistency requirements
The engine trusts your comparator. If it answers inconsistently, the specification says the resulting order is implementation-defined. The array still contains the same elements, but their order may differ between engines and even between array sizes in one engine. A comparator is consistent when it meets these conditions:
- Antisymmetric: if
compare(a, b) < 0, thencompare(b, a) > 0. - Transitive: if
ais beforebandbis beforec, thenais beforec. - Deterministic: the same pair always gives the same answer. No randomness, no reading mutable outside state.
- Pure: it must not modify the array or the elements.
Most comparator bugs violate one of these rules, as the following sections show.
Numbers
The standard numeric comparator subtracts:
const nums = [10, 1, 5, 100, -3, 2.5];
nums.sort((a, b) => a - b);
console.log(nums); // [-3, 1, 2.5, 5, 10, 100]
nums.sort((a, b) => b - a);
console.log(nums); // [100, 10, 5, 2.5, 1, -3]a - b is negative when a < b, which puts smaller values first. Swapping to b - a reverses the direction. JavaScript numbers are IEEE 754 doubles, so subtraction cannot overflow and flip the sign. This differs from 32-bit integer subtraction in languages like Java or C.
Where subtraction breaks: NaN
NaN - x is NaN, and a NaN result is treated as 0. So NaN looks "equal" to every number. That breaks transitivity: 1 equals NaN, NaN equals 5, but 1 comes before 5. The output order depends on where NaN started in the array.
If your data might contain NaN, decide explicitly where it goes:
const nanLast = (a, b) => {
const aNaN = Number.isNaN(a);
const bNaN = Number.isNaN(b);
if (aNaN || bNaN) return aNaN - bNaN; // true - false = 1, so NaN sorts after numbers
return a - b;
};
console.log([3, NaN, 1, NaN, 2].sort(nanLast)); // [1, 2, 3, NaN, NaN]Infinities are fine. Infinity - 5 is Infinity (positive), and Infinity - Infinity is NaN, which becomes 0. That is correct, because two infinities of the same sign are equal.
BigInt needs comparisons, not subtraction
a - b on two BigInts returns a BigInt, and ToNumber throws on a BigInt:
const big = [30n, 10n, 20n];
try {
big.sort((a, b) => a - b);
} catch (e) {
console.log(e instanceof TypeError); // true
}
big.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
console.log(big); // [10n, 20n, 30n]The three-way pattern a < b ? -1 : a > b ? 1 : 0 works for any type with meaningful < and >, so it is a safe fallback whenever subtraction does not fit.
Strings
Subtracting strings gives NaN, so (a, b) => a - b on strings returns 0 for every pair and leaves the array in its original order. Use the three-way pattern:
const words = ['pear', 'Apple', 'banana', 'apple'];
words.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
console.log(words); // ['Apple', 'apple', 'banana', 'pear']This compares UTF-16 code units, the same rule the default sort uses. Uppercase letters (65–90) come before lowercase (97–122), and accented letters land after z. For a case-insensitive order you can normalize first:
const ci = (a, b) => {
const x = a.toLowerCase();
const y = b.toLowerCase();
return x < y ? -1 : x > y ? 1 : 0;
};
console.log(['b', 'C', 'a'].sort(ci)); // ['a', 'b', 'C']Code-unit ordering suits identifiers, keys, and machine-readable values. For text shown to people, use localeCompare or Intl.Collator, covered in a later chapter.
Dates
Date objects convert to their millisecond timestamp through valueOf, so subtraction works:
const events = [
new Date('2026-03-01'),
new Date('2025-12-24'),
new Date('2026-01-15')
];
events.sort((a, b) => a - b);
console.log(events.map(d => d.toISOString().slice(0, 10)));
// ['2025-12-24', '2026-01-15', '2026-03-01']Writing a.getTime() - b.getTime() does the same thing and makes the intent clearer. Two gotchas apply here:
- An Invalid Date has a timestamp of
NaNand causes the same transitivity problem shown in the NaN section. Validate dates when you parse them, or use a NaN-aware comparator. - Date strings in full ISO 8601 format with the same time zone (such as
'2026-01-15T09:00:00Z') sort correctly as strings. Other formats like'1/15/2026'do not. If the strings vary in format, parse them first.
Objects: Compare by a Key
Objects have no natural order, so a comparator picks a property:
const products = [
{ name: 'Lamp', price: 35 },
{ name: 'Desk', price: 220 },
{ name: 'Mug', price: 9 }
];
products.sort((a, b) => a.price - b.price);
console.log(products.map(p => p.name)); // ['Mug', 'Lamp', 'Desk']When you sort by different keys in many places, a small factory function avoids repeating the same comparator:
const byKey = (getKey, direction = 1) => (a, b) => {
const x = getKey(a);
const y = getKey(b);
return direction * (x < y ? -1 : x > y ? 1 : 0);
};
const items = [
{ name: 'Lamp', price: 35 },
{ name: 'Desk', price: 220 },
{ name: 'Mug', price: 9 }
];
items.sort(byKey(p => p.name));
console.log(items.map(p => p.name)); // ['Desk', 'Lamp', 'Mug']
items.sort(byKey(p => p.price, -1));
console.log(items.map(p => p.name)); // ['Desk', 'Lamp', 'Mug']Because byKey uses < and >, it handles numbers, strings, and BigInts. To sort by a second key when the first key ties, see the chapter on sorting objects by multiple keys.
Missing values
A plain a.price - b.price turns null into 0 and undefined into NaN. So objects with price: null sort as if they were free, and objects missing price break transitivity. (The rule that undefined goes to the end applies only to array elements that are themselves undefined, not to missing properties.) Handle missing values deliberately:
const nullsLast = (compare) => (a, b) => {
const aMissing = a == null;
const bMissing = b == null;
if (aMissing || bMissing) return aMissing - bMissing;
return compare(a, b);
};
const rows = [{ p: 5 }, { p: null }, { p: 2 }, {}];
const byP = nullsLast((x, y) => x - y);
rows.sort((a, b) => byP(a.p, b.p));
console.log(rows.map(r => r.p)); // [2, 5, null, undefined]The two missing entries stay in their original relative order because they compare as equal and the sort is stable.
Common Mistakes
Returning a boolean
This is the most common comparator bug:
// Wrong: returns true/false, which become 1/0 and never negative
const bad = (a, b) => a > b;
// Right
const good = (a, b) => a - b;
const data = [5, 1, 4, 2, 3, 9, 7, 8, 6, 0, 11, 10];
console.log([...data].sort(good)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]A boolean comparator never returns a negative value. When a < b, it returns 0 ("equal") instead of saying a should come first. This violates antisymmetry. Depending on the engine's algorithm and the input, the output may look correct for small tests and come out wrong in production. Lint rules and TypeScript (which types the comparator as returning number) catch this mistake.
Randomness as a comparator
arr.sort(() => Math.random() - 0.5) is a common way to "shuffle" an array, but the comparator is not deterministic. The resulting distribution is biased, and how biased depends on the engine. Use a Fisher–Yates shuffle instead.
Reversing instead of flipping
arr.sort(cmp).reverse() does give descending order, but it also reverses the relative order of equal elements. That matters when you depend on stability. Flipping the comparator ((a, b) => cmp(b, a)) keeps ties in their original order. The stability chapter covers why this matters.
Mutating inside the comparator
A comparator that changes elements, logs to shared state, or reads a value that changes during the sort breaks the determinism rule. Keep comparators to pure reads.
Performance: How Often the Comparator Runs
V8 and other modern engines use TimSort or a similar merge-based algorithm that makes roughly n log₂ n comparisons. You can count them:
const arr = Array.from({ length: 1000 }, () => Math.floor(Math.random() * 1e6));
let calls = 0;
arr.sort((a, b) => {
calls++;
return a - b;
});
console.log(calls > 1000); // true
console.log(calls < 1000 * 10 + 1); // true, roughly 8,000-9,000 in practiceEach element takes part in many comparisons. If computing a key is expensive (parsing a date string, running a regex, normalizing Unicode), that work is repeated every time. The fix is to compute each key once. This technique is called decorate–sort–undecorate, also known as the Schwartzian transform:
const logs = [
'2026-03-01 boot',
'2025-12-24 deploy',
'2026-01-15 restart'
];
const sortedLogs = logs
.map(line => ({ line, key: Date.parse(line.slice(0, 10)) })) // decorate: one parse per item
.sort((a, b) => a.key - b.key) // sort on the cached key
.map(entry => entry.line); // undecorate
console.log(sortedLogs);
// ['2025-12-24 deploy', '2026-01-15 restart', '2026-03-01 boot']This uses n key computations instead of about 2·n log n. It also leaves logs unchanged, because .map created a new array before .sort ran. For small arrays or cheap keys, the plain comparator is simpler and fast enough.
Choosing a Comparator
| Data | Comparator | Watch for |
|---|---|---|
| Finite numbers | `(a, b) => a - b` | `NaN` values |
| BigInt | `a < b ? -1 : a > b ? 1 : 0` | Subtraction throws `TypeError` |
| Machine strings (IDs, keys) | `a < b ? -1 : a > b ? 1 : 0` | Case and accents order by code unit |
| Human-readable strings | `localeCompare` / `Intl.Collator` | Covered in a later chapter |
| Dates | `a.getTime() - b.getTime()` | Invalid Date gives `NaN` |
| Objects | Compare an extracted key | `null` and missing properties |
| Expensive keys | Decorate–sort–undecorate | Extra memory for the wrapper objects |
Exercise
A teammate writes scores.sort((a, b) => a < b) to sort numbers ascending. Their unit test with [2, 1] passes. Explain why the comparator is wrong and give a correct replacement.
Show answer
The comparator returns a boolean, which becomes 1 or 0 and is never negative. When a should come first it returns 0 ("equal") instead of a negative number, so it breaks antisymmetry. It also has the direction backwards, since true (1) for a < b would push smaller values later. The order a broken comparator produces is implementation-defined, so a two-element test passing proves nothing. Use scores.sort((a, b) => a - b).
Exercise
Write a comparator that sorts an array of objects shaped like { id: 3n } (BigInt ids) in descending order of id.
Show answer
(a, b) => (a.id > b.id ? -1 : a.id < b.id ? 1 : 0). Subtraction would return a BigInt, which sort cannot convert to a Number, so it would throw a TypeError. The three-way comparison returns plain numbers, and putting the larger id first gives descending order.
Exercise
An array of { name, joined } records stores joined as strings like '3/14/2024'. Sorting with (a, b) => Date.parse(a.joined) - Date.parse(b.joined) is slow on 200,000 records. Why, and how do you fix it?
Show answer
The comparator runs roughly n log n times, about 3.5 million calls for 200,000 items, and each call parses two strings. Parse each date once: map each record to { record, key: Date.parse(record.joined) }, sort by a.key - b.key, then map back to entry.record. Also check for NaN keys, because unparseable strings would break transitivity.