Sub topic 13
Copying and Combining Arrays Without Mutation
This chapter assumes you know the difference between mutating and non-mutating methods, how splice and sort work, and how spread syntax unpacks an array. The focus here is on the methods that give you a new array and leave the original unchanged, and on the limits of the copies they make.
Copying matters most when an array is shared. Examples include React state, a function argument, a cached result, or a config list that several modules import. If one caller sorts or splices that array in place, every other holder of the reference sees the change. Copying methods let you produce a changed version while every existing reference still points at the old data.
The Copying Toolkit at a Glance
| Task | Mutating method | Non-mutating equivalent | Added in |
|---|---|---|---|
| Copy all or part | none | `slice(start, end)`, `[...arr]` | ES3 / ES2015 |
| Combine arrays | `push(...other)` | `concat(other)`, `[...a, ...b]` | ES3 / ES2015 |
| Sort | `sort(fn)` | `toSorted(fn)` | ES2023 |
| Reverse | `reverse()` | `toReversed()` | ES2023 |
| Insert / remove / replace | `splice(i, n, ...items)` | `toSpliced(i, n, ...items)` | ES2023 |
| Replace one index | `arr[i] = v` | `with(i, v)` | ES2023 |
The ES2023 methods work in Node.js 20+ and in all current major browsers. On older runtimes, use slice() followed by the mutating method, for example arr.slice().sort(fn).
Copying a Whole Array or a Range with slice
slice(start, end) returns the elements from start up to, but not including, end. Negative indices count from the end. If you omit both arguments, you get a copy of the whole array.
const items = ['a', 'b', 'c', 'd', 'e'];
console.log(items.slice()); // ['a', 'b', 'c', 'd', 'e']
console.log(items.slice(1, 3)); // ['b', 'c']
console.log(items.slice(-2)); // ['d', 'e']
console.log(items.slice(3, 1)); // [] (start after end gives empty)
console.log(items); // unchangedDon't confuse slice with splice. slice takes an end index and never mutates. splice takes a delete count and always mutates.
Combining Arrays: concat vs Spread
Both concat and spread build a new array from several sources. They give the same result for plain arrays. They differ in how they treat other inputs.
const a = [1, 2];
const b = [3, 4];
console.log(a.concat(b, 5, [6, [7]])); // [1, 2, 3, 4, 5, 6, [7]]
console.log([...a, ...b, 5]); // [1, 2, 3, 4, 5]
console.log([0, ...a, 2.5, ...b]); // [0, 1, 2, 2.5, 3, 4]The rules:
concatflattens each array argument by exactly one level. A non-array argument, such as5, is added as a single element. An array nested inside an argument, such as[7], stays nested.- Spread unpacks any iterable, including strings,
Set,Map, and generators. Spreading a non-iterable such as a plain object or a number inside an array literal throws aTypeError. concatdoes not unpack iterables that are not arrays.[].concat(new Set([1, 2]))gives[Set], while[...new Set([1, 2])]gives[1, 2].
const tags = new Set(['js', 'web']);
console.log([].concat(tags)); // [Set(2) { 'js', 'web' }]
console.log([...tags]); // ['js', 'web']
console.log([...'hi']); // ['h', 'i']Spread also lets you place values anywhere in the new array, which reads better than chained concat calls. Use concat when an input might be either a single value or an array and you want both handled the same way.
The ES2023 Copying Methods
ES2023 added a copying version of each common mutating method. Each one returns a new array of the same length as its result and never touches the original.
const scores = [42, 7, 19, 88];
const sorted = scores.toSorted((x, y) => x - y);
const reversed = scores.toReversed();
const spliced = scores.toSpliced(1, 2, 100);
const updated = scores.with(-1, 0);
console.log(sorted); // [7, 19, 42, 88]
console.log(reversed); // [88, 19, 7, 42]
console.log(spliced); // [42, 100, 88]
console.log(updated); // [42, 7, 19, 0]
console.log(scores); // [42, 7, 19, 88]toSpliced returns the result, not the removed items
splice returns the removed elements. toSpliced returns the new array. If you need both the removed items and the new array, take the removed range with slice first:
const queue = ['t1', 't2', 't3', 't4'];
const taken = queue.slice(0, 2);
const rest = queue.toSpliced(0, 2);
console.log(taken); // ['t1', 't2']
console.log(rest); // ['t3', 't4']with() validates its index
Assigning arr[10] = v on a short array silently grows it and leaves holes. with() refuses to do that. It accepts negative indices like at(), but throws a RangeError if the index is outside the array.
const row = [1, 2, 3];
console.log(row.with(-3, 'first')); // ['first', 2, 3]
try {
row.with(5, 'x');
} catch (err) {
console.log(err instanceof RangeError); // true
}Holes become undefined
toSorted, toReversed, toSpliced, and with never return sparse arrays. Any hole in the source becomes undefined in the copy. slice and concat keep the holes.
const sparse = [1, , 3];
console.log(sparse.slice()); // [1, <1 empty item>, 3]
console.log(sparse.toReversed()); // [3, undefined, 1]Shallow Copies: What Is Actually Copied
Every method in this chapter makes a shallow copy. The new array is a separate container, but each slot holds the same value as before. When the elements are objects, both arrays point at the same objects.
const users = [{ name: 'Ana' }, { name: 'Ben' }];
const copy = [...users];
copy.push({ name: 'Cleo' });
console.log(users.length); // 2 (the container is separate)
copy[0].name = 'Anna';
console.log(users[0].name); // 'Anna' (the element is shared)To change one element without affecting the original, replace that element with a new object instead of editing it in place:
const renamed = users.map(u =>
u.name === 'Anna' ? { ...u, name: 'Ana' } : u
);
console.log(users[0].name); // 'Anna'
console.log(renamed[0].name); // 'Ana'
console.log(renamed[1] === users[1]); // true (unchanged items are reused)This pattern reuses the objects that did not change. It is cheap, and it lets libraries that compare by reference, such as React, detect exactly which items changed. If you need a fully independent copy of nested data, use structuredClone(users). It copies plain objects, arrays, Map, Set, and Date values deeply, and throws on functions and DOM nodes.
Choosing an Approach
| Situation | Use |
|---|---|
| Full copy before a mutating operation | `[...arr]` or `arr.slice()` |
| Sub-range | `slice(start, end)` |
| Merge arrays and add single values | `[...a, x, ...b]` |
| Merge inputs that may be arrays or single values | `concat` |
| Convert a `Set`, string, or other iterable | spread (or `Array.from`) |
| Sorted, reversed, or spliced version | `toSorted`, `toReversed`, `toSpliced` |
| Replace one element safely | `with(i, v)` |
| Independent nested data | `structuredClone` |
Copying costs O(n) time and memory for each call. In a hot loop over a large array, mutating a local array that you created yourself is fine, because no one else holds a reference to it. Copy at the boundaries, where data comes in from or goes out to other code.
Exercise
Given const list = [{ id: 1, done: false }, { id: 2, done: false }];, a teammate writes const next = list.with(0, list[0]); next[0].done = true; and expects list[0].done to remain false. What is printed by console.log(list[0].done), and how should the code be written so the original stays unchanged?
Show answer
It prints true. with makes a shallow copy, and next[0] is the same object as list[0], so setting done changes the shared object. Replace the element with a new object instead: const next = list.with(0, { ...list[0], done: true });. Now list[0].done stays false and next[1] === list[1] is still true.
Exercise
What do [1, 2].concat([3, [4]], 5) and [...[1, 2], ...new Set([3, 3, 4])] each return, and what does [1, 2, 3].toSpliced(1, 1) return compared with [1, 2, 3].splice(1, 1)?
Show answer
The concat call returns [1, 2, 3, [4], 5], because it flattens one level and adds 5 as a single element. The spread expression returns [1, 2, 3, 4], because the Set removes the duplicate 3. toSpliced(1, 1) returns the new array [1, 3] and leaves the source alone. splice(1, 1) returns the removed elements [2] and changes its array to [1, 3].