JavaScript Array Destructuring and Spread Operator
Learn array destructuring, rest elements, and the spread operator with practical examples. Covers swapping, cloning, merging, and function arguments. Free reference.
Patterns
Detailed Explanation
Array Destructuring and Spread
While not array methods per se, destructuring and the spread operator are essential patterns for working with arrays in modern JavaScript.
Array Destructuring
Extract values into individual variables:
const [first, second, third] = [1, 2, 3];
// first: 1, second: 2, third: 3
// Skip elements
const [a, , c] = [1, 2, 3];
// a: 1, c: 3
// Default values
const [x = 0, y = 0] = [42];
// x: 42, y: 0
Rest Elements
Collect remaining elements into an array:
const [head, ...tail] = [1, 2, 3, 4, 5];
// head: 1
// tail: [2, 3, 4, 5]
const [first, second, ...rest] = "hello".split("");
// first: "h", second: "e", rest: ["l", "l", "o"]
Swap Variables
let a = 1, b = 2;
[a, b] = [b, a];
// a: 2, b: 1
Spread Operator
Clone an array (shallow):
const original = [1, 2, 3];
const clone = [...original];
Merge arrays:
const merged = [...arr1, ...arr2, ...arr3];
Add elements immutably:
// Append
const withNew = [...items, newItem];
// Prepend
const withFirst = [newItem, ...items];
// Insert at index
const withInserted = [
...items.slice(0, index),
newItem,
...items.slice(index)
];
Spread into function arguments:
const nums = [5, 2, 8, 1, 9];
Math.max(...nums); // 9
// Equivalent to Math.max(5, 2, 8, 1, 9)
Performance Notes
- Spread creates shallow copies — same as
slice()andconcat() - For very large arrays (100k+ elements), spread in function calls can cause stack overflow
structuredClone()for deep copying instead of spread
Use Case
Use destructuring for clean variable assignment from arrays (React useState, function returns). Use the spread operator for immutable array operations in React state updates, merging data from multiple sources, and passing array elements as function arguments.