Sub topic 1
What sort() Does by Default
Calling sort() with no arguments looks like the obvious way to put an array in order. For strings it often does what you expect. For numbers it usually doesn't. This chapter explains what the default sort actually does, so later chapters can build on that when you write your own ordering rules.
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 changing a value in place (mutation) and creating a new value
The Surprise with Numbers
Here is the classic example:
const nums = [10, 1, 5, 100];
nums.sort();
console.log(nums); // [1, 10, 100, 5]
nums.sort((a, b) => a - b);
console.log(nums); // [1, 5, 10, 100]The first result is not a bug. The default sort never compares the numbers as numbers. It converts each element to a string and compares the strings. As strings, "10" and "100" both start with "1", so they come before "5". The same thing happens in a dictionary, where "apple" comes before "b".
The second call passes a comparator function, which takes over the ordering decision. The next chapter covers comparators in full. For now, remember that numeric data needs one.
The Algorithm in Plain Terms
When you call sort() without a comparator, the engine does the following:
- It moves
undefinedvalues to the end. They are never converted or compared. - It moves empty slots (holes in sparse arrays) after the
undefinedvalues. - It converts every other element to a string with
String(value). - It compares those strings one UTF-16 code unit at a time. A code unit is the 16-bit number JavaScript uses to store each piece of a string.
- It writes the result back into the same array.
What Code-Unit Order Means
Comparing code units is fast and predictable, but it is not alphabetical in the human sense. The code unit values decide everything:
| Characters | Code units (hex) | Consequence |
|---|---|---|
| `-` | 0x2D | Negative numbers start with a low character |
| `0`–`9` | 0x30–0x39 | Digits come before all letters |
| `A`–`Z` | 0x41–0x5A | Uppercase comes before lowercase |
| `a`–`z` | 0x61–0x7A | Lowercase comes after uppercase |
| `é` | 0xE9 | Accented letters come after `z` |
That table explains these results:
console.log(['banana', 'Cherry', 'apple'].sort());
// ['Cherry', 'apple', 'banana']
console.log(['zebra', 'éclair'].sort());
// ['zebra', 'éclair']
console.log([-1, -2, 3].sort());
// [-1, -2, 3] ("-1" < "-2" because '1' < '2')
console.log([true, false, null].sort());
// [false, null, true] (compared as "false", "null", "true")Characters outside the Basic Multilingual Plane, such as most emoji, are stored as two code units (a surrogate pair). The sort compares those halves separately, so the result follows the raw storage format. It does not follow any meaningful character order.
Undefined Values and Holes
undefined and empty slots are handled separately from everything else:
const mixed = [3, undefined, 1, , 2];
mixed.sort();
console.log(mixed); // [1, 2, 3, undefined, <1 empty item>] in Node.js
console.log(mixed.length); // 5null gets no special handling. It turns into the string "null" and sorts among the letters starting with "n".
sort() Mutates and Returns the Same Array
sort() reorders the array in place and returns a reference to that same array. It does not return a copy.
const original = [3, 1, 2];
const result = original.sort();
console.log(result === original); // true
console.log(original); // [1, 2, 3]A common mistake is writing const sorted = data.sort() and expecting data to stay unchanged. Both names now point to the same reordered array. A later chapter covers toSorted(), which returns a new array instead.
When the Default Is Fine
The default sort is a reasonable choice when all elements are strings, they share the same case, they use only unaccented ASCII letters, and the ordering is for a machine rather than a person. Examples include sorting keys for a stable hash or deduplicating identifiers. For numbers, dates, mixed case, or text that people will read, supply a comparator or use a locale-aware method.
Exercise
What does ['b', 'B', 'a', 10, 9].sort() return, and why?
Show answer
It returns [10, 9, 'B', 'a', 'b']. Each element becomes a string: "b", "B", "a", "10", "9". Ordering by code unit puts '1' (0x31) before '9' (0x39), both before 'B' (0x42), and 'B' before 'a' (0x61) and 'b' (0x62).
Exercise
After running const a = [5, 1]; const b = a.sort(); b.push(0);, what is a?
Show answer
a is [1, 5, 0]. sort() reorders a in place and returns the same array, so b and a are the same array, and pushing to b also changes a.