Lesson 77 – Rest Operator in JavaScript
What You’ll Learn
- What the rest operator is in JavaScript
- How to use it in function parameters and array/object destructuring
- Difference between rest and spread operators
Introduction
The rest operator (...) allows you to represent an indefinite number of arguments as an array or gather the "rest" of items in destructuring.
function showNumbers(...nums) {
console.log(nums);
}
showNumbers(1, 2, 3); // [1, 2, 3]
Syntax and Use Cases
1. Rest in Function Parameters
function sumAll(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sumAll(5, 10, 15)); // 30
- The function accepts any number of arguments and packs them into the
numbersarray.
2. Rest in Array Destructuring
const colors = ["red", "blue", "green", "yellow"];
const [primary, secondary, ...others] = colors;
console.log(primary); // "red"
console.log(secondary); // "blue"
console.log(others); // ["green", "yellow"]
- The rest operator groups remaining items into a new array.
3. Rest in Object Destructuring
const user = {
name: "Amina",
age: 25,
country: "Ghana",
profession: "Developer"
};
const { name, ...details } = user;
console.log(name); // "Amina"
console.log(details); // { age: 25, country: "Ghana", profession: "Developer" }
- Similar to arrays, the rest operator gathers leftover key-value pairs.
?Rest vs Spread
| Rest | Spread |
|---|---|
| Collects values into a group | Spreads out elements |
| Used in function parameters or destructuring | Used in function calls, arrays, or objects |
Try Your Hand
- Write a function called
multiplyAll()that multiplies all given numbers using rest parameters. - Use array destructuring and the rest operator to extract the first two items, and collect the remaining in a new array.
Summary
- The rest operator (
...) is used to collect remaining items. - It works in function parameters, arrays, and objects.
- Don’t confuse it with the spread operator, which is used to expand items.