Mutating vs non-mutating array methods in JavaScript
Intermediate · 3 min read
When you hand an array to a function, that function can do one of two things. It can build a new array and leave yours alone, or it can change yours in place. Changing something in place is called mutating it. Neither is wrong, but if you don't know which one you are calling, you get bugs where a list changes "by itself" somewhere far away in your program.
In this tutorial you will raise a list of fees both ways, then go through the common array methods and sort them into "changes the array" and "returns something new". Along the way you will meet the most famous surprise in JavaScript arrays: [10, 9, 1].sort() gives [1, 10, 9]. You need to know what arrays and functions are, and how map works.
Arrays are shared, not copied
When you assign an array to another variable, or pass it to a function, JavaScript doesn't copy it. Both names point at the same array:
const a = [1, 2];
const b = a;
b.push(3);
console.log(a); // [ 1, 2, 3 ]
So if a function mutates its input, the caller's array changes too. That's the whole reason this topic matters.
Two groups of methods
- Mutate:
sort,reverse,splice,push,pop,shift,unshift,fill. - Return something new:
map,filter,slice,concat, and the newertoSortedandtoReversed.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
92 A function that changes its input, and one that does not
fairRaise a list of fares two ways: one returning a new list, one editing the list it was given. Then show which array methods mutate, and what the bare sort() does to numbers.
Stuck? Three hints, smallest first
- 1.
mapreturns a new array; aforloop assigning intofees[i]does not. - 2.
sortandreversechange the array and return that same array. - 3.
sort()with no comparator compares text, not numbers.
Step 1: a raise that returns a new list
Fees are in kobo (100 kobo make one naira). The underscore in 200_00 only makes it easier to read.
const raise = (fees, byKobo) => fees.map((fee) => fee + byKobo);
const fees = [200_00, 350_00];
console.log(raise(fees, 50_00)); // [ 25000, 40000 ]
console.log(fees); // [ 20000, 35000 ]
map builds a fresh array from the results. The original fees is untouched, so any other code using it still sees the old prices.
Step 2: a raise that edits in place
function raiseInPlace(fees, byKobo) {
for (let i = 0; i < fees.length; i++) fees[i] += byKobo;
return fees;
}
const inPlace = [200_00, 350_00];
raiseInPlace(inPlace, 50_00);
console.log(inPlace); // [ 25000, 40000 ]
Assigning into fees[i] writes into the caller's array. Sometimes that is what you want, for example to save memory on a huge list. When you do it, say so in the name, as raiseInPlace does.
Step 3: sort mutates, and returns the same array
Here is the wrong turn. You want a sorted copy of some marks, so you write:
const marks = [70, 45, 88, 61];
const sorted = marks.sort((a, b) => a - b);
console.log(sorted); // [ 45, 61, 70, 88 ]
console.log(marks); // [ 45, 61, 70, 88 ]
console.log(sorted === marks); // true
sort changes the array in place and returns it. So sorted looks like a new array, but it is the very same one. marks has lost its original order.
Step 4: copy first
Make a copy with slice() (or [...marks]), and sort the copy:
const marks = [70, 45, 88, 61];
const sorted = marks.slice().sort((a, b) => a - b);
console.log(sorted); // [ 45, 61, 70, 88 ]
console.log(marks); // [ 70, 45, 88, 61 ]
Newer JavaScript also has marks.toSorted((a, b) => a - b), which returns a sorted copy in one call.
Step 5: the bare sort compares text
sort() with no function compares values as text, character by character, the way a dictionary would:
console.log([10, 9, 1].sort()); // [ 1, 10, 9 ]
console.log([10, 9, 1].sort((a, b) => a - b)); // [ 1, 9, 10 ]
As text, '10' comes before '9' because '1' comes before '9'. The compare function (a, b) => a - b returns a negative number when a should come first, so it sorts as numbers. For numbers, always pass one.
Step 6: push and concat
const stops = ['yaba'];
const pushed = stops.push('ikeja');
const joined = stops.concat('lekki');
console.log(pushed); // 2
console.log(stops); // [ 'yaba', 'ikeja' ]
console.log(joined); // [ 'yaba', 'ikeja', 'lekki' ]
push mutates and returns the new length, not the array. A common bug is const list = stops.push('x'), which gives you a number. concat leaves stops alone and returns a new, longer array.
The full solution
The answer panel sorts a copy and the original, compares push with concat, shows the bare sort() on numbers, and runs both raises. Press Run to see the output.
const marks = [70, 45, 88, 61];
// Pure: the input is copied before it is sorted.
const sorted = marks.slice().sort((a, b) => a - b);
// Mutating: sort edits in place, and hands back the very array it edited.
const mutable = [...marks];
const returned = mutable.sort((a, b) => a - b);
// push mutates and returns the new length; concat returns a new array.
const stops = ['yaba'];
const pushed = stops.push('ikeja');
const joined = stops.concat('lekki');
const raise = (fees, byKobo) => fees.map((fee) => fee + byKobo);
function raiseInPlace(fees, byKobo) {
for (let i = 0; i < fees.length; i++) fees[i] += byKobo;
return fees;
}
const fees = [200_00, 350_00];
const inPlace = [200_00, 350_00];
raiseInPlace(inPlace, 50_00);
console.log('sort() on numbers:', [10, 9, 1].sort());
console.log('push returned', pushed, 'and stops is now', stops);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a copy leaves the original in place', marks, [70, 45, 88, 61]);
test('and the copy is sorted', sorted, [45, 61, 70, 88]);
test('sort returns the very array it changed', returned === mutable, true);
test('the bare sort compares text, so 10 lands before 9', [10, 9, 1].sort(), [1, 10, 9]);
test('push hands back the new length, not the array', pushed, 2);
test('concat leaves its input alone', stops, ['yaba', 'ikeja']);
test('the pure raise gives a new list', raise(fees, 50_00), [25000, 40000]);
test('and the old one is untouched', fees, [20000, 35000]);
test('the mutating one edited the caller\u2019s array', inPlace, [25000, 40000]);
[10, 9, 1].sort() giving [1, 10, 9] is the one to memorise: with no comparator, sort converts every element to a string and compares those, so '10' < '9'. Numbers always need (a, b) => a - b.
The deeper habit is knowing which functions change what you handed them. sort, reverse, splice, push, fill all mutate; map, filter, concat, slice return something new. sort is the nastiest because it also returns the array, so const sorted = marks.sort(...) reads like a copy and is not — marks is sorted too, and any code depending on the original order is now broken. Copy first with slice() or [...marks], or use the newer toSorted. A mutating function is not wrong, but it should be obvious from its name, as raiseInPlace is.
Common mistakes
- Thinking
const sorted = list.sort()makes a copy. It sortslisttoo. Copy first or usetoSorted. - Sorting numbers without a compare function.
[10, 9, 1].sort()is[1, 10, 9]. - Using the result of
push. It is the new length, not the array.
Try it yourself
- Write
withoutFirst(list)that returns everything but the first item without changinglist. (Hint:slice(1).) - Reverse
['a', 'b', 'c']without changing it, in two ways:slice().reverse()andtoReversed(). - Write
discountInPlace(fees, percent)anddiscount(fees, percent), and show which one changes the caller's array.