Rest Elements in Nested Patterns
What you'll learn: How to use the rest operator (...) to collect remaining elements at any level of nested destructuring patterns.
The Core Idea
You've already seen the rest operator work at the "top level" of destructuring—grabbing leftover array elements or object properties. But the real power comes when you use rest inside nested structures. You can collect "remaining items" at any depth of your data structure, not just the outermost level.
Think of it like unpacking nested boxes: you can say "give me the first item from the outer box, then from the inner box take the first two items and put everything else into a separate pile." The ... operator creates that "everything else" pile wherever you place it in your pattern.
Examples at Different Nesting Levels
// Nested array with rest
const data = [1, [2, 3, 4, 5], 6];
const [first, [nestedFirst, ...nestedRest], last] = data;
// first = 1, nestedFirst = 2, nestedRest = [3, 4, 5], last = 6
// Nested object with rest
const user = {
name: 'Alice',
address: { city: 'NYC', state: 'NY', zip: '10001', country: 'USA' }
};
const { name, address: { city, ...addressRest } } = user;
// name = 'Alice', city = 'NYC'
// addressRest = { state: 'NY', zip: '10001', country: 'USA' }
// Mixed nesting
const complex = [{ a: 1, b: 2, c: 3 }, 'x', 'y'];
const [{ a, ...objRest }, ...arrayRest] = complex;
// a = 1, objRest = { b: 2, c: 3 }, arrayRest = ['x', 'y']
The rest operator must always come last in its respective pattern (whether array or object), but you can use it at multiple nesting levels simultaneously.
Key Takeaway: The rest operator (...) works at any depth in nested destructuring patterns, letting you collect remaining elements or properties wherever you need them, as long as it appears last in that specific level.