Collecting Remaining Elements
What you'll learn: How to use the rest pattern in destructuring to capture all leftover elements into a single collection.
When you destructure an array or object, you often only need the first few values. But what happens to everything else? The rest pattern (...) lets you collect all the remaining, unmatched elements into a new array or object—giving you both the specific items you want and everything that's left over in one operation.
How It Works
In array destructuring, rest gathers remaining elements into an array:
const colors = ['red', 'blue', 'green', 'yellow', 'purple'];
const [primary, secondary, ...others] = colors;
console.log(primary); // 'red'
console.log(secondary); // 'blue'
console.log(others); // ['green', 'yellow', 'purple']
In object destructuring, rest collects remaining properties into a new object:
const user = { name: 'Alice', age: 30, city: 'NYC', country: 'USA' };
const { name, age, ...location } = user;
console.log(name); // 'Alice'
console.log(age); // 30
console.log(location); // { city: 'NYC', country: 'USA' }
Think of It Like Sorting Mail
Imagine sorting mail: you pull out the urgent letters first, then dump everything else into a "rest of the mail" basket. The rest pattern does exactly that—extract what you need immediately, and bundle the remainder for later.
Why This Matters
This pattern is perfect when you want to split data into "what I need now" and "everything else," without manually slicing arrays or deleting object properties.
Key Takeaway: Use rest in destructuring (...variable) to collect all remaining array elements or object properties into a single, new collection.