Emmanuel Akinfulubi

JavaScriptArray

Which array methods mutate in JavaScript

Intermediate · 4 min read

Some array methods change the array you call them on. Others leave it alone and hand you a new value. Mixing the two up causes some of the most common bugs in JavaScript: a list that reorders itself somewhere else in the program, or a variable that holds a number when you expected an array.

In this tutorial you will sort the methods into the two groups, write a small test that proves which group each method is in, and then look at what each changing method actually returns. You should know arrays and arrow functions.

Mutating and copying

To mutate an array means to change it in place. Compare map, which makes a new array, with sort, which rearranges the one you have:

JavaScript

const a = [3, 1, 2];
const doubled = a.map((n) => n * 2);
console.log(a, doubled); // [ 3, 1, 2 ] [ 6, 2, 4 ]

a.sort();
console.log(a); // [ 1, 2, 3 ]

After map, a is unchanged. After sort, a itself is different. Every other part of the program that holds a sees the change too.

The list of methods that mutate is short enough to learn by heart. There are nine: push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin. Everything else, such as map, filter, slice, concat, flat and join, returns something new and leaves the array alone.

Comparing two arrays

To tell whether an array changed, we need to compare it with how it started. The exercise panel has a small helper called same built in. It turns both values into JSON text and compares the text, which is enough for short lists of numbers:

JavaScript

const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
console.log(same([3, 1, 2], [3, 1, 2])); // true
console.log(same([1, 2, 3], [3, 1, 2])); // false

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

43 Which methods mutate, and what they return

fair

Sort the array methods into the ones that change the array and the ones that return a new one. Then check the return value of each mutating method — none of them returns the array except sort, reverse and fill.

Stuck? Three hints, smallest first
  1. 1. The mutators are push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin. That is the whole list.
  2. 2. push and unshift return the new length; pop and shift return the element; splice returns an array of what it removed.
  3. 3. Test it rather than remembering it: run each method against a copy and see whether the copy changed.

Step 1: a test for "did it change?"

Rather than trust a list, test each method. changed takes an operation, runs it on a fresh [3, 1, 2], and reports whether the array is still [3, 1, 2] afterwards:

Step 1

const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);

const changed = (run) => {
  const a = [3, 1, 2];
  run(a);
  return !same(a, [3, 1, 2]);
};

console.log(changed((a) => a.push(9)));        // true
console.log(changed((a) => a.map((n) => n)));  // false

Each call gets its own new array, so one test can't spoil the next.

Step 2: test both groups

Put the operations in two lists and run changed on every one with map:

Step 2

const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const changed = (run) => {
  const a = [3, 1, 2];
  run(a);
  return !same(a, [3, 1, 2]);
};

const mutators = [
  (a) => a.push(9), (a) => a.pop(), (a) => a.shift(), (a) => a.unshift(0),
  (a) => a.splice(1, 1), (a) => a.sort(), (a) => a.reverse(), (a) => a.fill(0),
];
const copiers = [
  (a) => a.map((n) => n), (a) => a.filter(() => true), (a) => a.slice(),
  (a) => a.concat([4]), (a) => a.flat(), (a) => a.join('-'),
];

console.log(mutators.map(changed).every(Boolean)); // true
console.log(copiers.map(changed).some(Boolean));   // false

every(Boolean) asks "is every result true?" and some(Boolean) asks "is any result true?". Every mutator changed the array, and no copier did.

The test array matters. [3, 1, 2] is not already sorted or reversed, so sort and reverse really do move things. On [1, 2, 3], sort would leave it looking the same and the test would wrongly say "no change".

Step 3: push and unshift return a length

Now the second half of the exercise: what do the mutators give back? This is where the bugs live. A natural first guess is that push returns the bigger array:

Step 3

const xs = [1, 2, 3];
const bigger = xs.push(4);

console.log(bigger);         // 4
console.log(xs);             // [ 1, 2, 3, 4 ]
console.log([1].unshift(0)); // 2

bigger is the number 4, the new length. The array that grew is xs itself. unshift, which adds to the front, also returns the new length.

Step 4: pop, shift and splice return what they removed

Step 4

console.log([1, 2].pop());          // 2
console.log([1, 2].shift());        // 1
console.log([1, 2, 3].splice(0, 2)); // [ 1, 2 ]
console.log([].pop());              // undefined

pop hands back the last item and shift the first, one value each, not "the rest". splice(0, 2) removes two items starting at index 0 and returns an array of the items it removed. So const rest = xs.splice(0, 2) gives you the part you threw away, not the part that's left.

Popping an empty array doesn't throw an error. It returns undefined.

Step 5: sort, reverse and fill return the same array

Only three mutators return the array, and it is the very same array, not a copy:

Step 5

const a = [2, 1];
console.log(a.sort() === a);    // true
console.log(a.reverse() === a); // true
console.log(a.fill(0) === a);   // true

=== on arrays asks "is this the same object?" All three say yes. That makes const sorted = xs.sort() misleading: it reads like a sorted copy, but sorted and xs are two names for one array, and xs got sorted too. When you want a sorted copy, use [...xs].sort() or the newer toSorted().

The full solution

The panel runs changed on both groups, then prints what each mutator returns, with a note on every line. Press Run and compare it with the steps above.

The answer

// Run an operation against a fresh array and report whether it was changed.
const changed = (run) => {
  const a = [3, 1, 2];
  run(a);
  return !same(a, [3, 1, 2]);
};

const mutators = [
  (a) => a.push(9), (a) => a.pop(), (a) => a.shift(), (a) => a.unshift(0),
  (a) => a.splice(1, 1), (a) => a.sort(), (a) => a.reverse(), (a) => a.fill(0),
];

const copiers = [
  (a) => a.map((n) => n), (a) => a.filter(() => true), (a) => a.slice(),
  (a) => a.concat([4]), (a) => a.flat(), (a) => a.join('-'),
];

console.log('mutating methods changed the array:', mutators.map(changed));
console.log('copying methods left it alone      :', copiers.map(changed));
console.log('--- what the mutators hand back ---');
console.log("push(2)        ->", [1].push(2), '(the new length)');
console.log('pop()          ->', [1, 2].pop(), '(the element removed)');
console.log('shift()        ->', [1, 2].shift(), '(the first element)');
console.log('unshift(0)     ->', [1].unshift(0), '(the new length)');
console.log('splice(0, 2)   ->', [1, 2, 3].splice(0, 2), '(an array of what went)');
console.log('sort()         ->', [2, 1].sort(), '(the same array)');
console.log('pop() on empty ->', [].pop(), '(undefined, and no error)');

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.

9 checks

test('every mutating method changed the array', mutators.map(changed).every(Boolean), true);
test('and no copying method did', copiers.map(changed).some(Boolean), false);
test('push returns the new length', [1].push(2), 2);
test('unshift returns the new length too', [1].unshift(0), 2);
test('pop returns the element it removed', [1, 2].pop(), 2);
test('shift returns the first element', [1, 2].shift(), 1);
test('splice returns an array of what it removed', [1, 2, 3].splice(0, 2), [1, 2]);
test('sort, reverse and fill return the array itself', (() => { const a = [2, 1]; return [a.sort() === a, a.reverse() === a, a.fill(0) === a]; })(), [true, true, true]);
test('popping an empty array gives undefined rather than throwing', [].pop(), undefined);

Nine mutators, and the list is short enough to learn: push, pop, shift, unshift, splice, sort, reverse, fill, copyWithin. Everything else on Array.prototype returns something new and leaves the receiver alone.

The return values are where the real bugs come from, because only three of the nine give you back the array. const bigger = xs.push(4) gives a number, const rest = xs.shift() gives one element rather than the remainder, and const shorter = xs.splice(0, 2) gives the part you deleted. When a mutating call appears on the right-hand side of an assignment, read it twice.

Common mistakes

  • Treating push as if it returns the array. const list = xs.push(4) stores a number. Push first, then use xs.
  • Expecting shift or splice to return what's left. They return what was removed. The rest stays in the original array.
  • Assuming sort() makes a copy. It sorts in place and returns the same array, so the caller's data changes.

Try it yourself

  1. Add copyWithin to the mutators list as (a) => a.copyWithin(0, 1) and check that changed reports true.
  2. Find out what [1, 2, 3].splice(1, 0, 'x') returns, and what the array looks like afterwards.
  3. Rewrite const last = xs.pop() so that xs is not changed. (Hint: at(-1).)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.