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

Adding Elements Immutably with Spread

Use spread syntax to add items to the beginning, middle, or end of an array without mutation.

Adding Elements Immutably with Spread

You'll learn how to use the spread operator (...) to insert items anywhere in an array without changing the original.

The Core Idea

Remember how .push(), .unshift(), and .splice() modify the original array? Sometimes you want to add elements but preserve the original array unchanged. The spread syntax (...) lets you create a new array that includes all the old items plus your additions—without touching the original.

Think of it like making a photocopy of a list, then writing new items on the copy. The original list stays pristine.

Adding to the End

const original = [1, 2, 3];
const withEnd = [...original, 4, 5];
// original: [1, 2, 3] — unchanged
// withEnd: [1, 2, 3, 4, 5]

Adding to the Beginning

const original = [1, 2, 3];
const withStart = [0, ...original];
// original: [1, 2, 3] — unchanged
// withStart: [0, 1, 2, 3]

Adding to the Middle

Here's where it gets powerful—use slice() to split the array at the insertion point, then spread both pieces:

const original = [1, 2, 5, 6];
const withMiddle = [...original.slice(0, 2), 3, 4, ...original.slice(2)];
// original: [1, 2, 5, 6] — unchanged
// withMiddle: [1, 2, 3, 4, 5, 6]

You're spreading elements before index 2, adding new values, then spreading everything from index 2 onward.

Why This Matters

This technique is essential when working with immutable data patterns (common in React and functional programming). You get predictable behavior without accidental side effects.

Key Takeaway: Use spread syntax (...array) to add elements to any position in an array while keeping the original unchanged—spread the parts you want to keep and insert new values wherever needed.