Mutating vs. Non-Mutating Methods

Not all array methods behave the same way. Learn the difference between methods that mutate the original array and methods that return a brand new one.

May 1, 20262 min read3 / 4

The Essentials

  1. Mutating Methods: Methods like .push() change the original array in place.
  2. Non-Mutating Methods: Methods like .concat() leave the original array untouched and return a brand new array.
  3. Return Values: Pay attention to what an array method returns. .push() returns the new length of the array, not the array itself.

I have established that arrays are mutable, meaning you can change their contents after they are created. However, when you use built-in array spells (methods) to manipulate arrays, you need to be very careful.

Some methods mutate the original array. Other methods leave the original array completely untouched and give you a brand new array instead.

The .push() Method (Mutating)

Take a look at what happens when you use .push() to add an item to an array:

JavaScript
let numbers1 = [1, 2, 3]; let result1 = numbers1.push(4); console.log(numbers1); // Returns [1, 2, 3, 4] console.log(result1); // Returns 4

Two important things happened here:

  1. The original numbers1 array was mutated. It now permanently contains 4. You will sometimes hear developers say this method changes the array "in place."
  2. The result1 variable captured the return value of .push(), which is 4. push does not return the new array; it returns the new length of the array.

The .concat() Method (Non-Mutating)

Now take a look at what happens when you use .concat() to achieve a similar result:

JavaScript
let numbers2 = [1, 2, 3]; let result2 = numbers2.concat([4]); console.log(numbers2); // Returns [1, 2, 3] console.log(result2); // Returns [1, 2, 3, 4]

This behaved completely differently:

  1. The original numbers2 array was unchanged. It is still [1, 2, 3].
  2. The .concat() method evaluated the two arrays, squished them together, and conjured up a brand new array in memory. It then returned that new array, which was captured by result2.

Why This Matters

To JavaScript, these are two totally different operations. One manipulates an existing object in memory. The other conjures up a new object from scratch.

If you assume a method creates a new array when it actually mutates the original, you might accidentally destroy data you needed later. Conversely, if you assume a method mutates the original array but it actually returns a new one, you might wonder why your array never updated.

When in doubt, check MDN. The documentation will always explicitly tell you whether a method "changes the existing array" or "returns a new array."

Further Reading and Watching