Array Destructuring & Spread Operator
Destructuring extracts values from arrays into individual variables. The spread operator (...) copies and merges arrays. Both are essential ES6 features used everywhere in modern JavaScript and React.
Destructuring & Spread
- Destructuring — const [a, b, c] = [1, 2, 3]; extracts values by position
- Skip items — const [first, , third] = [1, 2, 3]; skips second element
- Rest — const [first, ...rest] = [1, 2, 3, 4]; rest = [2, 3, 4]
- Spread (...) copy — const copy = [...original]; creates a shallow copy
- Spread merge — const merged = [...arr1, ...arr2]; combines arrays
- Swap variables — [a, b] = [b, a]; elegant swap without temp variable
Destructuring & Spread Code
// Array destructuring
const colors = ["red", "green", "blue", "yellow"];
const [primary, secondary, ...others] = colors;
console.log(primary); // "red"
console.log(secondary); // "green"
console.log(others); // ["blue", "yellow"]
// Skip items
const [first, , third] = [10, 20, 30];
console.log(first, third); // 10 30
// Default values
const [a = 0, b = 0, c = 0] = [1, 2];
console.log(a, b, c); // 1, 2, 0
// Swap variables
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2, 1
// Spread — copy array
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3] — unchanged!
console.log(copy); // [1, 2, 3, 4]
// Spread — merge arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = [...arr1, ...arr2];
console.log(merged); // [1, 2, 3, 4, 5, 6]
// Spread — add items
const withNew = [0, ...arr1, 99];
console.log(withNew); // [0, 1, 2, 3, 99]Tip
Tip
Use destructuring in function parameters for cleaner code: function greet({ name, age }) { } instead of function greet(user) { const name = user.name; }. This pattern is used extensively in React component props.
Destructuring lets you unpack object properties and array elements in one line
Common Mistake
Warning
Spread creates a SHALLOW copy only. If the array contains objects, [...arr] copies the references, not the objects themselves. Modifying a nested object in the copy still affects the original. Use structuredClone() for deep copies.
Practice Task
Note
Practice destructuring: (1) Destructure the first two items from an array, rest into another variable. (2) Swap two variables using destructuring. (3) Use spread to merge two arrays and add an item in the middle. (4) Create a shallow copy and verify independence.
Quick Quiz
Key Takeaways
- Destructuring extracts values from arrays into individual variables.
- Destructuring — const [a, b, c] = [1, 2, 3]; extracts values by position
- Skip items — const [first, , third] = [1, 2, 3]; skips second element
- Rest — const [first, ...rest] = [1, 2, 3, 4]; rest = [2, 3, 4]