Rest Pattern Order Matters
You'll learn why the position of the rest element in destructuring determines exactly which values it captures.
Why Position Matters
When destructuring arrays or objects, the rest pattern (...) must always come last — but where you place the other variables before it dramatically changes what the rest captures.
Think of it like splitting a deck of cards: if you first deal out specific cards to named players, the "rest" pile contains only what's left over. Deal fewer cards first, and the rest pile grows. Deal more cards first, and the rest pile shrinks.
Position Controls What Gets Captured
const numbers = [10, 20, 30, 40, 50];
// Rest captures everything after first element
const [first, ...restOfAll] = numbers;
console.log(first); // 10
console.log(restOfAll); // [20, 30, 40, 50]
// Rest captures everything after first TWO elements
const [a, b, ...restOfSome] = numbers;
console.log(a); // 10
console.log(b); // 20
console.log(restOfSome); // [30, 40, 50]
// Rest captures everything after first THREE
const [x, y, z, ...restOfFew] = numbers;
console.log(x); // 10
console.log(y); // 20
console.log(z); // 30
console.log(restOfFew); // [40, 50]
Same Rule for Objects
const user = { id: 1, name: 'Alice', age: 30, city: 'NYC' };
// Capture id, rest gets everything else
const { id, ...userData } = user;
console.log(userData); // { name: 'Alice', age: 30, city: 'NYC' }
// Capture id AND name, rest gets even less
const { id: userId, name, ...otherData } = user;
console.log(otherData); // { age: 30, city: 'NYC' }
The more specific variables you extract before the rest, the fewer properties remain for rest to capture.
Key Takeaway: The rest pattern always captures what's "left over" — position your specific destructuring variables carefully to control exactly what ends up in the rest collection.