Course contentsShow
← JavaScript
Lesson 907 of 2,72320. Array Iteration and TransformationFree lesson

Avoiding Array.push, .pop, .shift, and .unshift

Learn why mutating methods cause bugs and how to replace them with immutable alternatives.

Avoiding Array.push, .pop, .shift, and .unshift

What you'll learn: How to replace mutating array methods with safer, immutable alternatives that prevent bugs.

Why Avoid These Methods?

You've learned that push(), pop(), shift(), and unshift() all mutate the original array. While convenient, these methods can introduce subtle bugs in larger applications—especially when multiple parts of your code reference the same array.

Immutable Alternatives

Instead of mutating arrays, create new ones:

Instead of push():

const numbers = [1, 2, 3];
const updated = [...numbers, 4]; // [1, 2, 3, 4]
// numbers is still [1, 2, 3]

Instead of unshift():

const numbers = [2, 3, 4];
const updated = [1, ...numbers]; // [1, 2, 3, 4]

Instead of pop():

const numbers = [1, 2, 3, 4];
const updated = numbers.slice(0, -1); // [1, 2, 3]

Instead of shift():

const numbers = [1, 2, 3, 4];
const updated = numbers.slice(1); // [2, 3, 4]

The Benefits

Think of arrays like shared documents. Mutating methods are like editing the original—everyone sees your changes (which might break their work). Immutable approaches create copies, leaving the original intact for anyone who needs it.

This pattern becomes crucial when working with React, Redux, or any code where predictable data flow matters.

Key Takeaway: Replace push(), pop(), shift(), and unshift() with the spread operator and slice() to create new arrays instead of mutating existing ones, preventing unexpected side effects in your code.