Sub topic 3
Comparators and the default string sort order
This chapter assumes you know JavaScript arrays and indexing, have used Array.prototype.sort, can write arrow functions, and understand the difference between primitive values and object references. It covers the comparator contract that sort and toSorted share. The next chapter covers what toSorted adds on top of that contract.
toSorted uses the same sorting algorithm as sort. The only difference is that it writes the result into a new array. Every ordering surprise you have seen with sort therefore also happens with toSorted. Most of those surprises come from two places: the default ordering used when you pass no comparator, and comparators that break the rules the engine relies on.
What happens when you pass no comparator
When you call sort() or toSorted() with no argument, the engine does not look at value types. It converts each element to a string and compares the strings by UTF-16 code unit, one character at a time from the left.
const scores = [40, 100, 1, 5];
console.log(scores.toSorted()); // [1, 100, 40, 5]
const temps = [-1, -2, 3];
console.log(temps.toSorted()); // [-1, -2, 3]
const words = ["banana", "apple", "Cherry"];
console.log(words.toSorted()); // ["Cherry", "apple", "banana"]Each result follows from comparing strings:
"100"comes before"40"because"1"comes before"4". The rest of the string is never compared."-1"comes before"-2"because the minus signs match and"1"comes before"2". Numerically, -2 is smaller."Cherry"comes first because uppercase letters (code units 65–90) are lower than lowercase letters (97–122).
The default order is fine when every element is a plain ASCII string and you want code-unit order, for example when sorting fixed-format IDs or ISO date strings like "2026-11-25". In nearly every other case you need a comparator.
How mixed values and `undefined` are ordered
The string conversion also applies to arrays that mix types. undefined is the one exception. The engine moves it to the end without converting it or passing it to your comparator.
const mixed = [10, 9, "8", undefined, null];
console.log(mixed.toSorted()); // [10, "8", 9, null, undefined]Here null becomes "null", which sorts after the digit strings because "n" (110) is higher than "9" (57). The undefined goes last because it is set aside before any comparison happens.
The comparator contract
A comparator is a function (a, b) => number. The engine uses the sign of the return value and ignores its size:
| Return value | Meaning |
|---|---|
| Negative (for example -1 or -42) | `a` goes before `b` |
| Positive (for example 1 or 0.5) | `a` goes after `b` |
| Zero | Keep `a` and `b` in their original relative order |
| `NaN` | Treated as zero |
Since ES2019 the sort has been required to be stable. Elements whose comparison returns zero keep the order they had in the input. Multi-key sorting depends on this, as shown below.
The specification also requires a comparator to be consistent. It must return the same answer for the same pair every time, compare(a, b) and compare(b, a) must have opposite signs, and the ordering must be transitive. If you break these rules, the specification calls the resulting order "implementation-defined". Different engines, or different array lengths in the same engine, can give different results. The method will not throw. It will just return a quietly wrong order.
Numeric comparators
For ordinary numbers, subtraction gives a correct sign:
const scores = [40, 100, 1, 5];
const ascending = scores.toSorted((a, b) => a - b);
const descending = scores.toSorted((a, b) => b - a);
console.log(ascending); // [1, 5, 40, 100]
console.log(descending); // [100, 40, 5, 1]Subtraction has failure modes, though.
NaN breaks consistency
If an element is NaN, every subtraction involving it returns NaN, which counts as zero. The comparator then reports NaN as "equal" to every number, even though those numbers are not equal to each other. That breaks transitivity, so the final order depends on the engine. Remove or map NaN before sorting, or give it an explicit position:
const readings = [3, NaN, 1, 2];
const nanLast = readings.toSorted((a, b) => {
if (Number.isNaN(a)) return Number.isNaN(b) ? 0 : 1;
if (Number.isNaN(b)) return -1;
return a - b;
});
console.log(nanLast); // [1, 2, 3, NaN]BigInt throws a TypeError
The engine converts the comparator's result with the specification's ToNumber operation, and ToNumber throws when it gets a BigInt. a - b on two BigInts returns a BigInt, so the sort throws:
const ids = [3n, 1n, 2n];
try {
ids.toSorted((a, b) => a - b);
} catch (err) {
console.log(err instanceof TypeError); // true
}
const sortedIds = ids.toSorted((a, b) => (a < b ? -1 : a > b ? 1 : 0));
console.log(sortedIds); // [1n, 2n, 3n]The three-way form a < b ? -1 : a > b ? 1 : 0 works for numbers, BigInts, and strings. Use it when you are not sure of the element type.
Boolean comparators
This is a common bug:
const wrong = (a, b) => a > b; // returns true or falsetrue becomes 1 and false becomes 0, so the comparator never returns a negative value. It can say "a after b" or "equal", but never "a before b". On small arrays it sometimes appears to work, which is why the bug survives code review. Always return a signed number.
String comparators
Code-unit order is rarely what a person expects to see. String.prototype.localeCompare compares according to locale rules, handling case and accented characters the way people read them:
const words = ["zebra", "éclair", "apple"];
console.log(words.toSorted()); // ["apple", "zebra", "éclair"]
console.log(words.toSorted((a, b) => a.localeCompare(b))); // ["apple", "éclair", "zebra"]Default sorting puts "éclair" last because "é" is code unit 233, which is higher than every ASCII letter.
For large arrays, or when you need options, create an Intl.Collator once and use its compare method. Its compare is already bound to the collator, so you can pass it directly:
const files = ["item10", "item2", "Item1"];
const collator = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
console.log(files.toSorted(collator.compare)); // ["Item1", "item2", "item10"]The numeric: true option compares runs of digits as numbers, so "item2" sorts before "item10". The sensitivity: "base" option ignores differences in case and accents when deciding equality. Calling localeCompare repeatedly with options can build that configuration again on every call. A collator builds it once.
Sorting objects by key
Comparators usually read a property from each element. For several keys, use ||. When the first comparison returns 0, || moves on to the next one:
const people = [
{ last: "Lovelace", first: "Ada", age: 36 },
{ last: "Hopper", first: "Grace", age: 85 },
{ last: "Lovelace", first: "Byron", age: 28 }
];
const byLastThenAge = people.toSorted(
(a, b) => a.last.localeCompare(b.last) || a.age - b.age
);
console.log(byLastThenAge.map((p) => p.first)); // ["Grace", "Byron", "Ada"]Because the sort is stable, a comparator that returns 0 for ties keeps those items in their input order. You can rely on that when the input is already ordered by a secondary key.
To reverse any comparator, swap its arguments instead of writing a second version:
const byAge = (a, b) => a.age - b.age;
const reverse = (compare) => (a, b) => compare(b, a);
const people = [{ age: 36 }, { age: 85 }, { age: 28 }];
console.log(people.toSorted(reverse(byAge)).map((p) => p.age)); // [85, 36, 28]Common errors at a glance
| Symptom | Cause | Fix |
|---|---|---|
| `[1, 100, 40, 5]` | No comparator, so string order is used | `(a, b) => a - b` |
| Order differs between browsers | Boolean or inconsistent comparator | Return a signed number every time |
| `TypeError` sorting BigInts | Subtraction returns a BigInt | Three-way `<` / `>` comparator |
| Uppercase before lowercase, accents last | Code-unit string order | `localeCompare` or `Intl.Collator` |
| `"item10"` before `"item2"` | Digits compared as characters | `Intl.Collator` with `numeric: true` |
| Order scrambled around `NaN` | `NaN` compares as equal to everything | Filter it out or give it a fixed position |
Exercise
What does [25, 3, 100, undefined, 7].toSorted() return, and why is undefined where it is?
Show answer
[100, 25, 3, 7, undefined]. With no comparator the numbers become the strings "25", "3", "100", and "7", which sort by code unit: "100" < "25" < "3" < "7". The undefined is moved to the end before any comparison, so it is never converted to a string.
Exercise
Write a comparator for an array of { name, price } objects that sorts by price from highest to lowest and breaks ties by name in English alphabetical order.
Show answer
(a, b) => b.price - a.price || a.name.localeCompare(b.name, "en"). Subtracting a.price from b.price gives descending order. When the prices are equal the result is 0, so || falls through to the name comparison.
Exercise
A teammate writes list.toSorted((a, b) => a > b) and says it passes the tests. Why is it still wrong?
Show answer
The comparator returns true or false, which become 1 or 0, so it never returns a negative number to say a goes before b. That breaks the comparator contract, and the specification then calls the result implementation-defined. It may work on small test arrays and fail on larger ones or in another engine. Return a signed number, such as (a, b) => (a < b ? -1 : a > b ? 1 : 0).