Sub topic 1
What sort() Does by Default
This chapter covers how Array.prototype.sort orders elements when you give it no arguments, how comparator functions change that order, and how to sort without changing the original array.
Prerequisites
This chapter assumes you know:
- JavaScript variables, functions, and arrow functions
- How to create an array and read elements by index
- Objects and property access
- The difference between mutating a value and creating a new one
The Default: String Comparison
When you call sort() with no arguments, it converts each element to a string and orders the strings by UTF-16 code units. The character "1" comes before "5", so "100" sorts before "5". This is why numbers come out in a surprising order:
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]sort() also mutates the array in place and returns the same array. It does not return a copy. Any undefined elements are moved to the end without being compared.
Comparator Functions
A comparator is a function (a, b) that returns a number:
| Return value | Meaning |
|---|---|
| Negative | `a` comes before `b` |
| Zero | Keep their relative order |
| Positive | `a` comes after `b` |
For numbers and Date objects, use a - b for ascending order (dates subtract as timestamps) and b - a for descending. For plain strings, use a.localeCompare(b).
Sorting Without Mutation
toSorted (ES2023) takes the same comparator but returns a new array and leaves the original unchanged. In older environments, sort a spread copy instead:
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
const copySorted = [...original].sort((a, b) => a - b);
console.log(original); // [3, 1, 2]
console.log(sorted); // [1, 2, 3]
console.log(copySorted); // [1, 2, 3]Use toSorted when other code holds a reference to the array, for example React state or a function argument you don't own.
Exercise
What does [25, 3, 200].sort() return, and how do you sort it descending numerically without changing the original array?
Show answer
It returns [200, 25, 3] because the strings "200" < "25" < "3" compare by their first characters. Use arr.toSorted((a, b) => b - a), which also gives [200, 25, 3] here but for a numeric reason, and it leaves arr unchanged.