Rest in Array Destructuring
What you'll learn: How to capture all remaining elements from an array into a single variable using rest syntax during destructuring.
The Core Idea
When destructuring an array, you might want to grab the first few elements individually while collecting everything else into a separate array. The rest operator (...) lets you do exactly that—it gathers all the remaining elements into a new array.
Think of it like sorting laundry: you pull out specific items you need right now (socks, shirt), then throw everything else into one basket for later.
Basic Syntax
const colors = ['red', 'blue', 'green', 'yellow', 'purple'];
const [first, second, ...others] = colors;
console.log(first); // 'red'
console.log(second); // 'blue'
console.log(others); // ['green', 'yellow', 'purple']
The ...others collects all remaining elements after first and second.
Important Rules
Rest must be last: The rest element must always be the final variable in your destructuring pattern.
const [head, ...rest] = [1, 2, 3, 4];
console.log(head); // 1
console.log(rest); // [2, 3, 4]
When There's Nothing Left
If no elements remain, rest gives you an empty array—never undefined:
const [a, b, ...remaining] = [10, 20];
console.log(remaining); // []
Practical Example
const [currentTask, ...backlog] = ['Write docs', 'Fix bugs', 'Review code', 'Deploy'];
console.log(`Working on: ${currentTask}`);
console.log(`Still to do: ${backlog.length} tasks`);
Key Takeaway: Use rest syntax (...variable) as the last element in array destructuring to collect all remaining values into a single array, making it easy to separate what you need now from what you'll handle later.