Sub topic 1
What sort() Does by Default
Array.prototype.sort() with no arguments is one of the most misread methods in JavaScript. It looks like it should "just sort," and with lowercase English words it often seems to. Call it on numbers, dates, mixed-case strings, or arrays with gaps, though, and the results look random until you understand the rule behind them. This chapter explains that rule exactly: what the default sort converts, how it compares, where it puts special values, and what it does to the array you call it on.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript variables, functions, and arrow functions
- Creating arrays and reading elements by index
- Objects and property access
- The difference between mutating a value and creating a new one
You do not need to know how to write a comparator yet. The next chapter covers comparators. Here the goal is to understand the behavior you get when you leave the comparator out.
The one-sentence rule
When you call sort() without a compare function, JavaScript:
- Sets aside
undefinedvalues and empty slots (holes). - Converts every remaining element to a string with
String(value). - Orders those strings by comparing their UTF-16 code units one at a time, left to right.
- Writes the sorted elements back into the same array, followed by the
undefinedvalues, followed by the holes.
The rest of the chapter follows from these four steps. The conversion to strings happens only for comparison. The array keeps its original values, numbers stay numbers, and only their order changes.
Why numbers come out "wrong"
Here is the classic surprise:
const nums = [10, 1, 5, 100];
nums.sort();
console.log(nums); // [1, 10, 100, 5]The sort compared "10", "1", "5", and "100" as text, the way a dictionary compares words. The first character decides the order unless it is a tie. "1", "10", and "100" all start with "1", which comes before "5". Among those three, the shorter one wins when the others start with it ("1" is a prefix of "10"), so the order is "1", "10", "100", "5".
The same rule causes some less obvious failures:
console.log([-1, -2, 3, 0].sort()); // [-1, -2, 0, 3]
console.log([0.5, 10, 2.25].sort()); // [0.5, 10, 2.25]
console.log([1e21, 5].sort()); // [1e+21, 5]
console.log([9, 80, 700].sort()); // [700, 80, 9]Each one has a clear explanation:
-1and-2become"-1"and"-2". Both start with-(code unit 0x2D), and then"1"comes before"2", so-1lands before-2. That is the reverse of numeric order. The-character also sorts before every digit, so all negative numbers cluster at the front.0.5becomes"0.5", and"0"comes before"1"and"2". Here the result happens to be numerically correct, which shows why testing with a few values can hide the bug.1e21stringifies as"1e+21", which starts with"1", so it sorts before5.[9, 80, 700]comes out fully reversed, because"7"<"8"<"9".
What "UTF-16 code units" means in practice
JavaScript strings are sequences of 16-bit UTF-16 code units. The default sort compares these numbers directly. It knows nothing about language, alphabet, or case. This has three practical effects.
Uppercase sorts before lowercase
In code-unit order, all uppercase ASCII letters (0x41 to 0x5A) come before all lowercase ones (0x61 to 0x7A):
console.log(['banana', 'Apple', 'cherry', 'apple'].sort());
// ['Apple', 'apple', 'banana', 'cherry']
console.log(['b', 'a', 'B', 'Z'].sort());
// ['B', 'Z', 'a', 'b']'Z' comes before 'a'. A human reader would never order a list that way.
Accented letters sort after z
Characters outside basic ASCII have larger code units, so they land after every unaccented Latin letter:
console.log(['é', 'e', 'z'].sort()); // ['e', 'z', 'é']
console.log(['Émile', 'Zoe', 'Adam'].sort()); // ['Adam', 'Zoe', 'Émile']é is U+00E9, which is greater than z (U+007A). A French reader expects é next to e. Fixing that is the job of localeCompare and Intl.Collator, which a later chapter covers.
Code units are not code points
Characters outside the Basic Multilingual Plane, such as most emoji, are stored as two code units called a surrogate pair. The default sort compares the first unit of that pair, not the character's real Unicode number:
const chars = ['\uFF5E', '😀'];
console.log(chars.sort()); // ['😀', '~']
console.log('😀'.codePointAt(0).toString(16)); // 1f600
console.log('😀'.charCodeAt(0).toString(16)); // d83d
console.log('\uFF5E'.charCodeAt(0).toString(16)); // ff5eBy code point, 😀 (U+1F600) is larger than ~ (U+FF5E). By code unit, its first half is 0xD83D, which is smaller than 0xFF5E, so it sorts first. This rarely matters, but it does explain occasional odd orderings in lists that mix emoji with CJK punctuation or full-width characters.
How other types are converted
Every non-undefined element goes through String(). Knowing what each type turns into lets you predict the result:
| Value | String used for comparison | Consequence |
|---|---|---|
| `10` | `"10"` | Sorts by digits as text |
| `-3` | `"-3"` | Negatives cluster first, in reverse magnitude order for same-length values |
| `NaN` | `"NaN"` | Sorts after digits and before lowercase letters |
| `Infinity` | `"Infinity"` | Sorts among words starting with "I" |
| `null` | `"null"` | Sorts as the word "null", not to the end |
| `true` / `false` | `"true"` / `"false"` | Sorts as words |
| `{}` | `"[object Object]"` | All plain objects compare equal |
| `[1, 2]` | `"1,2"` | Nested arrays compare by joined contents |
| `new Date(...)` | `"Mon Jan 01 2024 ..."` | Sorts by weekday name |
| `Symbol()` | throws `TypeError` | Sort fails |
| `undefined` | not converted | Always moved to the end |
A few of these deserve a closer look.
null is not treated like undefined
undefined gets special handling, but null does not:
console.log(['o', null, 'm', undefined, 'a'].sort());
// ['a', 'm', null, 'o', undefined]null sorted between 'm' and 'o' because it was compared as "null". Only undefined was moved to the end.
Mixed types follow their string forms
console.log([true, 'apple', 5, NaN, false].sort());
// [5, NaN, 'apple', false, true]The strings are "5", "NaN", "apple", "false", and "true". Digits (0x30 to 0x39) come before uppercase N (0x4E), which comes before lowercase letters. The original values are kept, so 5 is still a number and false is still a boolean.
Dates sort by day of the week
This is the most dangerous case, because a list of dates looks like it should sort chronologically:
const dates = [
new Date(2024, 0, 1), // Monday
new Date(2024, 0, 2), // Tuesday
new Date(2024, 0, 5) // Friday
];
dates.sort();
console.log(dates.map(d => d.getDate())); // [5, 1, 2]Date.prototype.toString() produces strings like "Fri Jan 05 2024 00:00:00 GMT+0000 ...". The default sort compares "Fri", "Mon", and "Tue", so January 5 comes first. Dates need a comparator. The next chapter shows how to write one.
Objects compare equal
Every plain object becomes "[object Object]", so the default sort sees them all as equal:
const users = [{ name: 'Cy' }, { name: 'Ana' }, { name: 'Bo' }];
users.sort();
console.log(users.map(u => u.name)); // ['Cy', 'Ana', 'Bo']Nothing moves. The order stays the same because sorting has been guaranteed stable since ES2019: elements that compare equal keep their original relative order. A later chapter explains stability and why it matters. For now, the takeaway is that sort() on objects silently does nothing useful.
Symbols throw
String(Symbol('a')) works, but the implicit conversion the sort uses (the spec's ToString operation) throws on symbols:
try {
[Symbol('a'), Symbol('b')].sort();
} catch (err) {
console.log(err instanceof TypeError); // true
}An array containing a single symbol does not throw, because the sort never compares anything. This means the error only shows up once the array grows past one element.
undefined and holes go to the end
The default sort never converts undefined. Before comparing, it collects the defined values, sorts them, and writes them back. Then it writes the undefined values. It also deletes the trailing slots so that holes (indexes that were never assigned) end up at the very end.
const arr = [3, , 1, undefined, 2];
console.log(arr.length); // 5
arr.sort();
console.log(arr); // [1, 2, 3, undefined, <1 empty item>]
console.log(arr.length); // 5
console.log(3 in arr); // true (index 3 holds undefined)
console.log(4 in arr); // false (index 4 is a hole)The length does not change, and holes are never turned into undefined. Holes simply move to the end. This rule also applies when you pass a comparator: your function is never called with undefined or with a hole. If you need undefined values somewhere other than the end, you have to replace them with a sentinel value before sorting.
sort() mutates and returns the same array
The default sort, like every sort() call, rearranges the array in place. Its return value is the same array object, not a copy:
const original = ['c', 'a', 'b'];
const result = original.sort();
console.log(result); // ['a', 'b', 'c']
console.log(original); // ['a', 'b', 'c']
console.log(result === original); // trueThis causes bugs when code assumes sort() returns a new array:
function topNames(names) {
return names.sort().slice(0, 2);
}
const roster = ['Zed', 'Amy', 'Kim'];
console.log(topNames(roster)); // ['Amy', 'Kim']
console.log(roster); // ['Amy', 'Kim', 'Zed'] (caller's array changed)The caller's roster was reordered as a side effect. If the array is shared, for example as React state, a function argument, or a module-level constant, mutation like this is usually a bug. A later chapter covers toSorted() and the copy-then-sort pattern, which avoid it.
When the default is actually fine
The default sort is correct when code-unit order is what you want:
- Arrays of strings that you know are all lowercase ASCII, or all uppercase ASCII, such as identifiers or enum values.
- Machine-generated keys where any consistent order will do, such as deduplicating or grouping before a merge.
- ISO 8601 date strings like
"2024-01-05", whose fixed-width, most-significant-first format makes text order equal chronological order.
const isoDates = ['2024-03-15', '2023-12-01', '2024-01-05'];
console.log(isoDates.sort()); // ['2023-12-01', '2024-01-05', '2024-03-15']Fixed-width ISO strings work. A non-padded format like "2024-1-5" does not, because "1-5" and "12-01" no longer line up digit for digit.
Typed arrays such as Int32Array and Float64Array are an exception: their sort() compares numerically by default. A later chapter covers them. For ordinary arrays, assume the default sort is wrong for anything that is not plain text.
Summary of the default behavior
- Elements are compared as strings produced by
String(), using UTF-16 code-unit order. - Numbers, dates, booleans, and
nullall sort by their text form, which rarely matches what you want. - Uppercase comes before lowercase, and accented letters come after
z. - Plain objects all compare equal, so they keep their order.
- Symbols throw a
TypeErroronce two need comparing. undefinedvalues go to the end, followed by holes. Neither is passed to a comparator.- The array is sorted in place, and the return value is the same array.
Exercise
Predict the output of console.log([25, -5, 100, -50, 3].sort()); and explain each position.
Show answer
[-5, -50, 100, 25, 3]. The strings are "25", "-5", "100", "-50", "3". The "-" character (0x2D) sorts before every digit, so the negatives come first. "-5" is a prefix of "-50", so "-5" comes before "-50". Among the rest, "1" < "2" < "3", giving "100", "25", "3".
Exercise
What does this code print, and why? const a = ['b', undefined, null, , 'a']; a.sort(); console.log(a, a.length);
Show answer
It prints ['a', 'b', null, undefined, <1 empty item>] 5. null is compared as the string "null", which sorts after "a" and "b". undefined is not converted and goes after all defined values. The hole at index 3 moves to the very end and stays a hole. The length stays 5.
Exercise
A teammate writes const latest = events.sort()[events.length - 1]; where events is an array of Date objects, intending to get the most recent event. Name the two problems with this line.
Show answer
First, the default sort compares dates by their toString() output, which begins with the weekday name, so the order is by "Fri", "Mon", "Sat" and so on, not by time. The last element is whichever date falls on the alphabetically last weekday ("Wed"), not the latest date. Second, sort() mutates events in place, so every other piece of code holding that array now sees it reordered.