Course contentsShow
← JavaScript
Lesson 999 of 2,72322. Spread and RestFree lesson

Adding Elements Without Mutation

Insert elements at arbitrary positions in arrays using spread, avoiding push and splice.

Adding Elements Without Mutation

You'll learn how to insert elements at any position in an array without changing the original array, using spread instead of mutation methods like push() or splice().

The Challenge

You've learned to add elements at the beginning or end with spread, but what if you need to insert an element at index 2, or 5, or anywhere in the middle? The old way would be splice(), but that mutates the original array.

The Spread and Slice Solution

Think of it like cutting a sandwich in half, adding a new ingredient, then putting it back together — but you're actually making a new sandwich, leaving the original untouched.

Here's the pattern:

const original = ['a', 'b', 'e', 'f'];

// Insert 'c' and 'd' at index 2
const updated = [
  ...original.slice(0, 2),  // Everything before index 2
  'c',
  'd',
  ...original.slice(2)      // Everything from index 2 onward
];

console.log(updated);  // ['a', 'b', 'c', 'd', 'e', 'f']
console.log(original); // ['a', 'b', 'e', 'f'] — unchanged!

How It Works

  1. slice(0, 2) extracts elements before your insertion point
  2. Spread ... unpacks those elements
  3. Add your new element(s) in the middle
  4. slice(2) extracts everything from the insertion point onward
  5. Spread ... unpacks those too
  6. The array literal [] creates a brand new array

You can insert multiple elements, or even spread another array at that position.

Key Takeaway: Use [...arr.slice(0, index), newItem, ...arr.slice(index)] to insert elements at any position without mutating the original array — giving you full control while maintaining immutability.