Spread Operator
The Spread Operator (...) 🌟
Why this matters: real apps constantly copy and merge arrays/objects without mutating the originals—Redux state, React props, configuration. Spread makes immutable updates short and easy to read.
The spread operator expands an array or object into individual elements.
Why Do We Need It?
The Problem: Copying Arrays
const original = [1, 2, 3];
const copy = original; // ❌ Not a copy!
copy.push(4);
console.log(original); // [1, 2, 3, 4] - Original changed!
The Solution: Spread
const original = [1, 2, 3];
const copy = [...original]; // ✅ Real copy!
copy.push(4);
console.log(original); // [1, 2, 3] - Original unchanged!
How It Works
... "spreads out" the elements:
const numbers = [1, 2, 3];
console.log(...numbers); // 1 2 3 (not [1, 2, 3])
Common Uses
1. Copy Arrays
const original = [1, 2, 3];
const copy = [...original];
2. Merge Arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]
3. Add Elements
const numbers = [2, 3, 4];
const withEnds = [1, ...numbers, 5]; // [1, 2, 3, 4, 5]
4. Copy Objects
const person = { name: "Alex", age: 25 };
const copy = { ...person };
5. Merge Objects
const defaults = { theme: "dark", lang: "en" };
const user = { lang: "es" };
const settings = { ...defaults, ...user };
// { theme: "dark", lang: "es" }
Real-World Use: Function Arguments
const numbers = [5, 2, 8, 1, 9];
const max = Math.max(...numbers); // 9
// Math.max(5, 2, 8, 1, 9)
Your Turn!
Merge two arrays into one using spread.