Course contentsShow
← JavaScript
Lesson 920 of 2,72321. DestructuringFree lesson

Destructuring the Rest with ... Operator

Capturing remaining array elements into a new array using the rest pattern.

Destructuring the Rest with ... Operator

You'll learn how to capture all remaining array elements into a new array using the rest pattern during destructuring.

The Core Idea

When destructuring an array, you might only need the first few elements by name, but still want to keep the "leftovers" together. The rest operator (...) lets you scoop up all remaining elements into a new array. This is like taking a few items off the top of a pile and putting everything else into a separate container.

How It Works

The rest operator must be the last element in your destructuring pattern:

const numbers = [1, 2, 3, 4, 5];
const [first, second, ...remaining] = numbers;

console.log(first);      // 1
console.log(second);     // 2
console.log(remaining);  // [3, 4, 5]

Notice how remaining captured elements at index 2, 3, and 4 into a new array.

Combining with Element Skipping

You can skip elements and still use the rest operator:

const letters = ['a', 'b', 'c', 'd', 'e'];
const [firstLetter, , thirdLetter, ...rest] = letters;

console.log(firstLetter);  // 'a'
console.log(thirdLetter);  // 'c'
console.log(rest);         // ['d', 'e']

When There's Nothing Left

If all elements are already captured, the rest array is simply empty:

const short = [1, 2];
const [a, b, ...others] = short;

console.log(others);  // []

Key Takeaway: The rest operator (...) in array destructuring collects all remaining unassigned elements into a new array, and it must always appear last in the destructuring pattern.