Rest parameters
- Node.js course
- Beginner
- Lesson 75/116
- 5 min
Learn to take a variable number of arguments with ...args.
Rest parameters
A rest parameter gathers a variable number of arguments into a single array. It is written with ... before the parameter name. The function receives these arguments as an array.
Syntax: function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }. In sum(1, 2, 3), nums becomes [1, 2, 3]; the result is 6. You can pass as many arguments as you like.
A rest parameter must always be the last in the parameter list. You cannot write more than one. function f(a, ...rest) is valid; function f(...rest, a) is a syntax error.
Rest versus arguments
Before rest parameters, JavaScript had an old object called arguments. It holds all arguments but is not a real array; array methods like map and filter do not work on it. Modern code prefers rest parameters.
A rest parameter is a real array: operations like nums.map(...), nums.length, nums[0] work directly. It also takes only the 'remaining' arguments; named parameters before rest stay separate.
Example: function f(first, ...rest). Here first takes the first argument and rest takes the rest as an array. In f('a', 'b', 'c'), first='a' and rest=['b','c'].
Practice Sum a variable number of values
Define a function sum(...nums). Its body sums the nums array with reduce (initial 0) and returns the result. Print the result of sum(10, 20, 30, 40) with console.log.
Starter code
// Define sum with a rest parameter and print the call resultSample solution
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(10, 20, 30, 40));Expected output
100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the rest parts
| Term | Meaning |
|---|---|
... |
Rest operator |
nums |
Name for gathered arguments |
[1, 2, 3] |
Value of nums |
last parameter |
Position of rest |
2 What does a rest parameter gather?
- All objects
- The first argument
- Remaining arguments into an array Correct answer
- Only numbers
Explanation: rest gathers all remaining arguments into a single array.
3 Sum with reduce
function sum(...nums) {
return nums.____((a, b) => a + b, 0);
}
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
Explanation: nums.reduce folds the array into a single value.