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.
The Essentials
- Mutating Methods: Methods like
.push()change the original array in place. - Non-Mutating Methods: Methods like
.concat()leave the original array untouched and return a brand new array. - 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:
let numbers1 = [1, 2, 3];
let result1 = numbers1.push(4);
console.log(numbers1); // Returns [1, 2, 3, 4]
console.log(result1); // Returns 4Two important things happened here:
- The original
numbers1array was mutated. It now permanently contains4. You will sometimes hear developers say this method changes the array "in place." - The
result1variable captured the return value of.push(), which is4.pushdoes 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:
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:
- The original
numbers2array was unchanged. It is still[1, 2, 3]. - 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 byresult2.
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
- MDN: Array.prototype.push()
- MDN: Array.prototype.concat()
- FrontendMasters: JavaScript First Steps - The source course for this foundational concept.
Keep reading