Array Destructuring with Rest in JavaScript Explained
rest in JavaScript lets you unpack values from an array into variables, while collecting the remaining items into a new array using the ...rest syntax. This helps you easily separate the first few elements from the rest without manual slicing.How It Works
Imagine you have a box of fruits and you want to take out the first apple and banana, but keep the rest of the fruits together in another smaller box. Array destructuring with rest in JavaScript works similarly. You pick specific elements from the start of the array and gather all remaining elements into a new array using the ...rest syntax.
This syntax uses three dots (...) before a variable name to collect all leftover items after extracting the named elements. It makes your code cleaner and easier to read compared to manually slicing arrays.
Example
This example shows how to extract the first two elements from an array and collect the rest into another array.
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']; const [first, second, ...rest] = fruits; console.log(first); // apple console.log(second); // banana console.log(rest); // ['cherry', 'date', 'elderberry']
When to Use
Use array destructuring with rest when you want to separate a few known elements from an array and keep the remaining elements grouped together. This is helpful when processing lists where the first items have special meaning, like headers or priority tasks, and the rest are general items.
For example, in a to-do app, you might want to get the first task to show as the current task and keep the rest for later. It also simplifies working with function arguments or splitting data into parts without extra code.
Key Points
- The
...restsyntax collects remaining array elements into a new array. - It must be the last element in the destructuring pattern.
- Helps write cleaner and more readable code when handling arrays.
- Works only with iterable objects like arrays.
Key Takeaways
...rest in array destructuring to gather leftover elements into a new array.