Sub topic 3
Sorting Without Mutation: toSorted and Copies
This chapter assumes you can write a comparator function. A comparator is a function (a, b) that returns a negative number, zero, or a positive number. It also assumes you know the difference between changing a value in place and creating a new one. Here you will learn why sort() changing its array in place causes bugs, how toSorted() avoids that, and which edge cases set the two apart.
The Problem: sort() Changes the Array It Is Called On
Array.prototype.sort sorts in place. It rearranges the elements of the array you call it on, then returns that same array. It does not return a new one. Many developers read this line as "make a sorted version":
const scores = [42, 7, 19];
const ranked = scores.sort((a, b) => b - a);
console.log(ranked === scores); // true
console.log(scores); // [42, 19, 7]ranked and scores are two names for one array. The original order is gone. If anything else in your program needed it, such as a display list, a cache, or a log of insertion order, that part of the program now sees sorted data.
The function-parameter trap
The bug is hardest to spot when the sort happens inside a function that receives an array from somewhere else:
function topThree(list) {
return list.sort((a, b) => b - a).slice(0, 3);
}
const prices = [5, 30, 12, 8, 25];
console.log(topThree(prices)); // [30, 25, 12]
console.log(prices); // [30, 25, 12, 8, 5]Nothing in the name topThree tells the caller that it reorders prices. Arrays are passed by reference, so list and prices point to the same object. This side effect is a common source of bugs that only show up later, far from the line that caused them.
Where this bites hardest
- UI state. React, Vue, Redux and similar libraries often detect changes by comparing references. Sorting state in place keeps the reference the same, so the framework may not re-render. Even if it does, you have also corrupted the previous state.
- Shared module data. A config array exported from one module and sorted in another changes for every importer.
- Memoized or cached results. If a cache hands out an array and a caller sorts it, every later cache hit returns the reordered version.
- Iteration. Sorting an array while another loop is walking over it gives confusing results.
toSorted(): A Sorted Copy in One Call
ES2023 added Array.prototype.toSorted. It takes the same optional comparator as sort(). It returns a new array with the elements in sorted order and leaves the original untouched.
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
console.log(original); // [3, 1, 2]
console.log(sorted); // [1, 2, 3]
console.log(sorted === original); // falseHere is the earlier helper rewritten without the side effect:
function topThree(list) {
return list.toSorted((a, b) => b - a).slice(0, 3);
}
const prices = [5, 30, 12, 8, 25];
console.log(topThree(prices)); // [30, 25, 12]
console.log(prices); // [5, 30, 12, 8, 25]toSorted() orders elements exactly as sort() does. It uses the same string-based default when you give no comparator, the same rules for your comparator, and the same stable ordering. The only differences are where the result goes and a few edge cases covered below.
Availability
toSorted() is supported in Chrome and Edge 110+, Firefox 115+, Safari 16+, and Node.js 20+. If you must support older runtimes, copy first and then sort the copy (see the next section), or use a polyfill such as core-js. TypeScript needs "lib": ["ES2023"] or later in tsconfig.json. Without it, TypeScript reports toSorted as a missing property.
The Classic Approach: Copy, Then sort()
Before ES2023, the standard way to sort without mutation was to make a copy and call sort() on the copy. The original is safe because the copy is a different array.
const original = [3, 1, 2];
const viaSpread = [...original].sort((a, b) => a - b);
const viaSlice = original.slice().sort((a, b) => a - b);
const viaFrom = Array.from(original).sort((a, b) => a - b);
console.log(original); // [3, 1, 2]
console.log(viaSpread); // [1, 2, 3]
console.log(viaSlice); // [1, 2, 3]
console.log(viaFrom); // [1, 2, 3]All three give the same result on an ordinary array. They differ on edge cases:
| Copy method | Holes in sparse arrays | Array subclasses | Works on array-likes and iterables |
|---|---|---|---|
| `[...arr]` | Turned into `undefined` | Always a plain `Array` | Iterables only |
| `arr.slice()` | Kept as holes | Keeps the subclass (via `Symbol.species`) | Only with `Array.prototype.slice.call(x)` |
| `Array.from(arr)` | Turned into `undefined` | Plain `Array` (unless called as `Sub.from`) | Both |
| `arr.toSorted()` | Turned into `undefined` | Always a plain `Array` | Only with `Array.prototype.toSorted.call(x)` |
A small helper lets you use toSorted() when it exists and fall back otherwise:
function sortedCopy(arr, compare) {
return typeof arr.toSorted === 'function'
? arr.toSorted(compare)
: [...arr].sort(compare);
}
console.log(sortedCopy([10, 1, 5], (a, b) => a - b)); // [1, 5, 10]Passing undefined as the comparator is fine for both methods. Both then fall back to the default string comparison.
Gotcha: The Copy Is Shallow
toSorted() and every copy technique above make a shallow copy. The new array is a different container, but it holds the same element values. For primitives (numbers, strings, booleans) that makes no difference. For objects, both arrays point to the same objects.
const users = [
{ name: 'Bo', visits: 2 },
{ name: 'Ana', visits: 5 }
];
const byVisits = users.toSorted((a, b) => b.visits - a.visits);
console.log(byVisits[0] === users[1]); // true: same object
byVisits[0].visits = 99;
console.log(users[1].visits); // 99toSorted() protects the order of the original array. It does not protect the contents of its elements. If you plan to change the sorted objects, map them to new objects first:
const users = [
{ name: 'Bo', visits: 2 },
{ name: 'Ana', visits: 5 }
];
const ranked = users
.toSorted((a, b) => b.visits - a.visits)
.map((u, i) => ({ ...u, rank: i + 1 }));
console.log(ranked); // [{ name: 'Ana', visits: 5, rank: 1 }, { name: 'Bo', visits: 2, rank: 2 }]
console.log(users[0]); // { name: 'Bo', visits: 2 }For nested data that needs a full independent copy, use structuredClone(users) before sorting. It costs more, so use it only when you really need deep independence.
Edge Cases Where sort() and toSorted() Differ
Sparse arrays
A sparse array has holes: indexes that were never assigned. sort() moves holes to the end and keeps them as holes. toSorted() always returns a dense array, so holes become real undefined values. Both put undefined after every other value, and neither passes undefined to your comparator.
const a = [3, , 1];
a.sort();
console.log(a.length); // 3
console.log(2 in a); // false: index 2 is still a hole
const b = [3, , 1];
const c = b.toSorted();
console.log(c); // [1, 3, undefined]
console.log(2 in c); // true: index 2 holds undefinedThis matters only if your code later uses in, Object.keys, or forEach, which skip holes but visit undefined.
Frozen arrays
sort() has to write to the array, so it throws on a frozen array. toSorted() only reads from the original, so it works:
const frozen = Object.freeze([3, 1, 2]);
console.log(frozen.toSorted()); // [1, 2, 3]
try {
frozen.sort();
} catch (e) {
console.log(e instanceof TypeError); // true
}This makes toSorted() the natural choice for data you have frozen on purpose, such as constants or immutable state.
Array subclasses
toSorted() always returns a plain Array, even when you call it on a subclass instance. slice() respects Symbol.species and keeps the subclass. sort() returns the instance itself.
class Playlist extends Array {}
const p = Playlist.from([3, 1, 2]);
console.log(p.toSorted() instanceof Playlist); // false
console.log(p.slice().sort() instanceof Playlist); // trueIf your subclass adds methods you need on the result, use slice().sort() or wrap the result with Playlist.from(...).
Array-like objects
Like most array methods, toSorted() is generic. You can call it on any object that has a length and indexed properties:
const arrayLike = { length: 3, 0: 'c', 1: 'a', 2: 'b' };
console.log(Array.prototype.toSorted.call(arrayLike)); // ['a', 'b', 'c']
console.log(arrayLike[0]); // 'c'Invalid comparators
Both methods throw a TypeError right away if the comparator is neither a function nor undefined. They throw before reading or copying anything:
try {
[2, 1].toSorted('desc');
} catch (e) {
console.log(e instanceof TypeError); // true
}Cost: Is the Copy Expensive?
toSorted() allocates a new array of length n. Sorting itself takes O(n log n) comparisons, so the O(n) copy rarely matters for speed. Engines also commonly use extra working memory during an in-place sort, which shrinks the gap further. The copy matters when:
- the array is very large (millions of elements) and memory is tight, or
- you sort in a hot loop that runs thousands of times per second and creates garbage each time.
In those cases, sorting in place an array that you own is a reasonable optimization. Outside them, choose clarity and avoid the side effect.
When Mutation Is Fine
Sorting in place is not wrong in itself. The problem is sorting an array that someone else still relies on. sort() is perfectly safe when the array was just created and no other code holds a reference to it:
const orders = [
{ id: 1, total: 40 },
{ id: 2, total: 15 },
{ id: 3, total: 90 }
];
// filter() already returned a fresh array, so sorting it in place harms nothing.
const bigOrders = orders
.filter(o => o.total > 20)
.sort((a, b) => b.total - a.total);
console.log(bigOrders.map(o => o.id)); // [3, 1]
console.log(orders.map(o => o.id)); // [1, 2, 3]filter, map, slice, concat, and Array.from all return new arrays. A sort() chained directly after them changes only that new array.
Related Copying Methods
toSorted() arrived in ES2023 together with copying versions of three other mutating methods. They follow the same pattern: same behavior, but they return a new array.
| Mutating | Non-mutating (ES2023) | What it does |
|---|---|---|
| `sort(cmp)` | `toSorted(cmp)` | Sorted order |
| `reverse()` | `toReversed()` | Reversed order |
| `splice(i, n, ...items)` | `toSpliced(i, n, ...items)` | Remove or insert elements (returns the new array, not the removed items) |
| `arr[i] = v` | `with(i, v)` | Replace one index |
const nums = [1, 2, 3];
console.log(nums.toReversed()); // [3, 2, 1]
console.log(nums.toSorted((a, b) => b - a)); // [3, 2, 1]
console.log(nums.with(0, 9)); // [9, 2, 3]
console.log(nums.toSpliced(1, 1)); // [1, 3]
console.log(nums); // [1, 2, 3]A common mistake is writing arr.toSorted(cmp).reverse() when you want descending order. It works, because reverse() mutates only the new array. Still, flipping the comparator ((a, b) => b - a) is clearer and saves a pass over the data. With a stable sort it also keeps equal elements in their original relative order, while reversing afterward flips them.
Summary of Rules
sort()reorders the array in place and returns the same reference.toSorted()returns a new array and leaves the original's order unchanged.- Both copies are shallow. Objects inside are shared between the old and new arrays.
toSorted()fills holes withundefined, works on frozen arrays, and always returns a plainArray.- In environments without
toSorted(), use[...arr].sort(cmp)orarr.slice().sort(cmp). - Call
sort()in place only on arrays you just created or fully own.
Exercise
A teammate writes function cheapest(items) { return items.sort((a, b) => a.price - b.price)[0]; } and calls it from a React component that passes its products state array. What two problems does this cause, and what is the smallest fix?
Show answer
First, it reorders the caller's products array as a hidden side effect, so anything else that renders products now shows it sorted by price. Second, the state array is mutated in place without a new reference, which breaks React's change detection and corrupts the previous state. The smallest fix is to replace sort with toSorted: return items.toSorted((a, b) => a.price - b.price)[0];. For older runtimes, use [...items].sort(...). (Finding the minimum with a single loop or reduce would avoid sorting altogether.)
Exercise
Given const tasks = [{ title: 'B', done: false }, { title: 'A', done: false }]; const sorted = tasks.toSorted((x, y) => x.title.localeCompare(y.title)); sorted[0].done = true;, what does tasks[1].done print, and why?
Show answer
It prints true. toSorted makes a shallow copy, so sorted[0] is the same object as tasks[1] (the task titled 'A'). Setting a property on it changes the object that both arrays share. Only the order of tasks is protected.
Exercise
Predict the output of const a = Object.freeze([2, , 1]); const b = a.toSorted(); console.log(b, 1 in b, b.length); and explain what would happen if you called a.sort() instead.
Show answer
It logs [1, 2, undefined] true 3. toSorted reads the frozen array without writing to it, puts the defined values in sorted order, and turns the hole into a real undefined at the end, so every index exists. Calling a.sort() throws a TypeError, because sorting in place has to write to the frozen array's indexes.