Copying arrays without mutation
A JavaScript function that changes the array it was given is harder to test than one that returns a new array, because the caller has to remember what the first call did to it. The language now has a group of array methods that return a new array and leave the receiver alone: toSorted, toReversed, with and toSpliced. They are the in-place methods of the previous lessons with a new array as the result.
This lesson covers the copy itself first, because a copied array of objects still shares those objects, then the four methods one by one. The spread copy is the fifth way, and it stays useful for the cases the methods do not cover.
A copy with the spread syntax
The spread syntax copies the items of an array into a new array, and the copy and the original are two different objects with equal contents. The copy is one level deep: an item that is itself an object is shared, so a change through the copy is visible through the original. The program prints both facts.
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log('the copy:', copy.join(','));
console.log('the original:', original.join(','));
console.log('a different object:', copy !== original);
const sameContents = [1, 2, 3];
console.log('equal contents, not equal objects:', JSON.stringify(sameContents) === JSON.stringify(original), sameContents === original);
const nested = [{ name: 'ada' }];
const shallow = [...nested];
shallow[0].name = 'grace';
console.log('the shared object changed:', nested[0].name);
node spread.js
the copy: 1,2,3,4
the original: 1,2,3
a different object: true
equal contents, not equal objects: true false
the shared object changed: grace
The push reached the copy and not the original, because the two are separate objects. The fourth line is the pair of comparisons that is easy to mix up: the contents are equal and the objects are not, since === on arrays asks whether it is the same array. The last line is the limit of every shallow copy: the array was copied and the object inside it was not, so a deep copy is a different tool for that case.
toSorted and toReversed
toSorted takes the comparator of sort and returns a sorted copy, toReversed takes no argument and returns a reversed copy. Neither changes the array it is called on, so the same source gives as many results as a program needs.
const scores = [30, 10, 20];
const sorted = scores.toSorted((a, b) => a - b);
const reversed = scores.toReversed();
console.log('toSorted:', sorted.join(','));
console.log('toReversed:', reversed.join(','));
console.log('the original:', scores.join(','));
console.log('three different arrays:', new Set([scores, sorted, reversed]).size);
node tosorted.js
toSorted: 10,20,30
toReversed: 20,10,30
the original: 30,10,20
three different arrays: 3
One source array, two results and one original that is still in its first order. The last line counts the three names as three objects in a Set, which works because a Set compares its values by identity and every array here is a different object. The pattern is worth keeping: the methods of this lesson never share the outer array with the source, and the results can be kept side by side.
with replaces one item
with(index, value) returns a copy in which the item at that position is replaced, and a negative index counts from the end. There is no in-place version of it, and an index that is out of range throws a RangeError instead of quietly adding an item.
const letters = ['a', 'b', 'c'];
const changed = letters.with(1, 'B');
console.log('with(1, B):', changed.join(','));
console.log('the original:', letters.join(','));
console.log('with a negative index:', letters.with(-1, 'C').join(','));
try {
letters.with(3, 'z');
} catch (error) {
console.log(error.name + ': ' + error.message);
}
node with.js
with(1, B): a,B,c
the original: a,b,c
with a negative index: a,b,C
RangeError: Invalid index : 3
The first and the third line are copies with one position changed, and the second line proves the source was not touched. The error is the useful part: a length of three has no index 3, and a silent append here would hide a mistake in the position. Compared with letters[1] = 'B', which changes the array and returns the value, the method says in its call that the result is a new array.
toSpliced
toSpliced takes the arguments of splice and returns the array that would have been left behind, with the removed items gone and the new ones in their place. The negative start counts from the end as it does for splice, and the source array keeps every item it had.
const days = ['mon', 'tue', 'wed', 'thu'];
console.log('remove one:', days.toSpliced(1, 1).join(','));
console.log('insert one:', days.toSpliced(1, 0, 'x').join(','));
console.log('replace two:', days.toSpliced(1, 2, 'mid').join(','));
console.log('from the end:', days.toSpliced(-2, 2).join(','));
console.log('the original:', days.join(','));
const removed = days.splice(0, 1);
console.log('splice without the to returns and changes:', JSON.stringify(removed), days.join(','));
node tospliced.js
remove one: mon,wed,thu
insert one: mon,x,tue,wed,thu
replace two: mon,mid,thu
from the end: mon,tue
the original: mon,tue,wed,thu
splice without the to returns and changes: ["mon"] tue,wed,thu
Four calls and four different arrays, with the source unchanged until the last call. That last line is the old method: it returned the removed item and changed the array in place, so the value and the effect both have to be kept in mind. The pair is a good summary of the whole lesson, since the same arguments give a result in one case and a result plus a change in the other.
Exercises
- Copy the original in spread.js with Array.from instead of the spread and print the length. Is the copy still a different object?
- Sort [3, 1, 2] with toSorted and then reverse the result with toReversed. Which array does each call leave alone?
- Call with(0, "x") and with(-4, "x") on an array of three. Which call throws and what does the message say?
- Replace the two removed items in tospliced.js with two new ones in one call. What does the result look like?
- Write a function without(array, index) that returns a copy with one item removed, using one method of this lesson. Which one is it?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
[...[1, 2]]give?Answer
A new array with the same two items
The spread builds a new array and copies the items into it, so the object is different.
-
What does this program print?
const a = [2, 1]; const b = a.toReversed(); console.log(a.join(","), b.join(","));Answer
2,1 1,2
toReversed returns the copy in the other order and leaves the source alone.
-
What does
[1, 2, 3].with(1, "x")give?Answer
[1, "x", 3]
The value replaces the item at index 1, and the result is a new array.
-
What does
[1, 2].with(2, 0)do?Answer
Throws a RangeError, because there is no index 2
with only replaces a position that exists, so an index equal to the length is out of range.
-
What does
[1, 2, 3].toSpliced(0, 1)give?Answer
[2, 3]
The method returns the array that would be left after the removal, and the source keeps its three items.
-
What does this program print?
const a = [{ n: 1 }]; const b = [...a]; b[0].n = 2; console.log(a[0].n);Answer
2
The spread copies the array and not the objects in it, so a change through the copy is visible in the original.
-
What does this program print?
const a = [1, 2]; const b = a; b.push(3); console.log(a.length);Answer
3
The second name holds the same array, so the push is visible through both names.
-
What does this program print?
const a = [1, 2, 3, 4]; console.log(a.toSpliced(1, 2, "x").join(","), a.length);Answer
1,x,4 4
Two items from index 1 are replaced by one in the copy, and the source keeps its four items.
-
What does
[1, 2, 3].with(-1, 0)give?Answer
[1, 2, 0]
A negative index counts from the end, so -1 is the last position.
-
Why does a pure function prefer
toSortedoversort?Answer
It returns a new array, so the argument of the caller keeps its order
A pure function must not change its arguments, and sort changes the array it is called on.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev