Sub topic 2
The copying methods added in ES2023
This chapter assumes you know JavaScript arrays and indexing, how Array.prototype.sort and Array.prototype.splice behave, arrow functions, and the difference between primitive values and object references. The previous chapter showed how in-place mutation causes bugs. This one covers the group of methods ES2023 added to fix that, the rules they all share, and how each one maps to the mutating method it replaces. Later chapters cover each method in detail.
The "Change Array by Copy" proposal
ES2023 (ECMAScript 2023, published in June 2023) added four methods to Array.prototype. They came from a TC39 proposal called Change Array by Copy. The idea is simple. Each mutating array operation that people often want as a copy gets a non-mutating twin. The twin takes the same arguments, returns a new array, and leaves the receiver alone. The receiver is the array you call the method on.
The proposal started as a spin-off from the Records and Tuples proposal. Tuples are immutable, so they needed methods like "sorted copy" and "copy with one element replaced". The authors saw that ordinary arrays would benefit from the same methods, so they moved them into their own proposal and shipped them on Array.prototype first.
| Mutating method | Copying twin | What the twin returns |
|---|---|---|
| `arr.sort(compare)` | `arr.toSorted(compare)` | A new sorted array |
| `arr.reverse()` | `arr.toReversed()` | A new reversed array |
| `arr.splice(start, deleteCount, ...items)` | `arr.toSpliced(start, deleteCount, ...items)` | The new array after the change |
| `arr[index] = value` | `arr.with(index, value)` | A new array with one slot replaced |
The naming follows a pattern. Three methods use a to prefix plus a past participle: toSorted, toReversed, toSpliced. You read arr.toSorted() as "arr, turned into its sorted version". Bracket assignment is syntax, not a method, so it had no name to adapt. Its twin is called with, read as "arr with index 2 set to 6".
All four methods at a glance
The following script runs in any runtime that supports ES2023, such as Node.js 20 or later. Each call leaves original unchanged.
const original = [3, 1, 4, 1, 5];
const sorted = original.toSorted((a, b) => a - b);
const reversed = original.toReversed();
const spliced = original.toSpliced(1, 2, "x");
const replaced = original.with(0, 9);
console.log(sorted); // [1, 1, 3, 4, 5]
console.log(reversed); // [5, 1, 4, 1, 3]
console.log(spliced); // [3, "x", 1, 5]
console.log(replaced); // [9, 1, 4, 1, 5]
console.log(original); // [3, 1, 4, 1, 5] (unchanged)Compare this with the mutating versions. If you ran original.sort(...), original.reverse(), and original.splice(1, 2, "x") in sequence, each call would work on the result of the previous one, and every variable pointing at original would see each change. With the copying methods, each call starts from the same untouched input.
The shared contract
The four methods follow the same rules. If you learn the rules once, you can predict how any of them behaves.
Rule 1: the receiver is never modified
None of the methods write to the array you call them on. No element is reassigned or reordered, and length stays the same.
Rule 2: the result is always a new array
Each call returns a fresh array, even when the operation changes nothing. The new array is never the same object as the receiver.
const nums = [1, 2, 3];
console.log(nums.toSorted() === nums); // false
console.log(nums.toReversed() === nums); // false
console.log(nums.toSpliced(0, 0) === nums); // false
console.log(nums.with(0, 1) === nums); // false
console.log(nums.sort() === nums); // true (sort returns the receiver)The last line shows a common trap with sort. Because sort returns its receiver, const b = a.sort() looks like it makes a sorted copy. It doesn't. a and b are the same array. toSorted removes that trap.
Rule 3: arguments match the mutating method
toSorted takes the same optional comparator as sort. toSpliced takes start, deleteCount, and any items to insert, just like splice. with takes an index and a value, the two parts of arr[index] = value. You don't need to learn new argument rules, only a new return value.
Rule 4: the return value is the changed array
This rule matters most for toSpliced. splice returns the elements it deleted, while toSpliced returns the full resulting array. If you swap one for the other without changing the surrounding code, the code will quietly do the wrong thing.
const letters = ["a", "b", "c", "d"];
const removedBySplice = [...letters].splice(1, 2);
const resultOfToSpliced = letters.toSpliced(1, 2);
console.log(removedBySplice); // ["b", "c"] (the deleted elements)
console.log(resultOfToSpliced); // ["a", "d"] (the array after deletion)If you need the deleted elements as well, use slice(start, start + deleteCount) on the original.
Rule 5: copies are shallow
The new array holds the same values as the old one. When those values are objects, both arrays point at the same objects. The methods copy the array structure, not the elements inside it. The chapter on shallow copies covers what this means for nested data.
Rule 6: the result is a plain Array
The methods always build a normal Array, even when called on an array subclass or an array-like object. They don't look up Symbol.species, unlike map, filter, and slice. A later chapter covers why this design choice was made.
What the proposal left out
Several other array methods mutate their receiver: push, pop, shift, unshift, fill, and copyWithin. ES2023 has no toPushed or toFilled. The proposal kept its scope small on purpose. Existing syntax and methods already give clean copies for the most common of these operations:
| Mutating call | Existing non-mutating equivalent |
|---|---|
| `arr.push(x)` | `[...arr, x]` or `arr.concat([x])` |
| `arr.unshift(x)` | `[x, ...arr]` |
| `arr.pop()` | `arr.slice(0, -1)` |
| `arr.shift()` | `arr.slice(1)` |
| `arr.fill(v, s, e)` | `arr.map((x, i) => (i >= s && i < e ? v : x))` |
toSpliced can also express all of the first four, for example arr.toSpliced(arr.length, 0, x) for a push. Spread and slice are shorter and easier to read in those cases, though.
When the old methods are still the right choice
The copying methods allocate a new array on every call. In most application code that cost is small and worth paying for code that is easier to reason about. In-place methods still make sense in a few cases:
- You own the array outright, such as a local buffer created in the same function that nobody else can see.
- You are sorting a very large array in a hot loop and have measured that the extra allocation matters.
- You build up a result step by step before returning it, where mutating a private accumulator is simpler than a chain of copies.
A useful rule of thumb: mutate only arrays you created and haven't shared yet. Copy any array that came from outside the current function, such as props, state, function arguments, or module-level data.
Checking for support
All four methods are available in Chrome 110, Firefox 115, Safari 16, and Node.js 20 and later. Older runtimes throw a TypeError such as "arr.toSorted is not a function". A quick check looks like this:
const hasChangeArrayByCopy =
typeof Array.prototype.toSorted === "function" &&
typeof Array.prototype.toReversed === "function" &&
typeof Array.prototype.toSpliced === "function" &&
typeof Array.prototype.with === "function";
console.log(hasChangeArrayByCopy); // true in Node.js 20+The chapter on runtime support covers fallbacks and polyfills.
Exercise
A teammate replaces const removed = items.splice(2, 1); with const removed = items.toSpliced(2, 1); to avoid mutating items. What does removed now contain, and how should the code be written to get the removed element without mutating items?
Show answer
removed now holds the whole array with index 2 removed, not the removed element, because toSpliced returns the resulting array while splice returns the deleted elements. To get the removed element without mutation, use items.slice(2, 3). If the shortened array is also needed, use items.toSpliced(2, 1) as a separate value.
Exercise
Given const a = [2, 1]; const b = a.sort(); const c = a.toSorted();, what do a === b and a === c evaluate to, and why?
Show answer
a === b is true because sort sorts in place and returns its receiver. a === c is false because toSorted always returns a new array, even though a is already sorted by that point.
Exercise
Why does ES2023 not include a toPushed method, and what is the idiomatic way to get a copy of arr with x appended?
Show answer
The proposal kept its scope to operations that had no clean non-mutating form. Appending already has one: [...arr, x] (or arr.concat([x])). Both return a new array and leave arr unchanged.