Sub topic 8
Collecting Arguments with Rest Parameters
This chapter assumes you can declare and call functions, work with arrays, and read template literals. It also builds on the previous chapter about the legacy arguments object.
The Problem Rest Parameters Solve
Some functions need to accept any number of arguments, such as a function that sums numbers or one that logs several messages. The arguments object can handle this, but it is only array-like. It has no map, filter, or reduce, it always holds every argument, including the ones already bound to named parameters, and arrow functions don't get their own.
A rest parameter is a final parameter written with three dots (...name). It gathers all remaining arguments into a real Array.
function sum(first, ...rest) {
return rest.reduce((total, n) => total + n, first);
}
console.log(sum(1, 2, 3, 4)); // 10
console.log(sum(5)); // 5, rest is []How Arguments Are Bound
JavaScript fills the named parameters from left to right. Whatever arguments are left over go into the rest array. If nothing is left over, the rest parameter is an empty array. It is never undefined.
Because rest is a genuine array, you can use array methods on it directly:
function tagAll(tag, ...items) {
return items.map((item) => `${tag}:${item}`);
}
console.log(tagAll("fruit", "apple", "pear")); // ["fruit:apple", "fruit:pear"]
const logAll = (...messages) => messages.forEach((m) => console.log(m));
logAll("one", "two"); // logs "one", then "two"The arrow function logAll works even though arrows have no arguments object.
Syntax Rules and Common Errors
| Rule | Invalid example | Error |
|---|---|---|
| Rest must be the last parameter | `function f(...a, b) {}` | SyntaxError |
| Only one rest parameter is allowed | `function f(...a, ...b) {}` | SyntaxError |
| No trailing comma after rest | `function f(...a,) {}` | SyntaxError |
| Rest cannot have a default | `function f(...a = []) {}` | SyntaxError |
When to Use a Rest Parameter
A rest parameter fits when the extra values are all the same kind of thing, such as numbers to add or items to tag. If the extra inputs are separate settings with different meanings, an options object (covered later) is clearer.
Exercise
What does collect("a") return for function collect(head, ...tail) { return [head, tail.length]; }, and why?
Show answer
It returns ["a", 0]. The string "a" binds to head, and no arguments remain, so tail is an empty array with length 0.
Exercise
Rewrite function max() { return Math.max.apply(null, arguments); } as an arrow function that uses a rest parameter and works with any number of numbers.
Show answer
const max = (...nums) => Math.max.apply(null, nums); The rest parameter nums gives the arrow function a real array of its arguments, which arrows otherwise lack. The next chapter shows a shorter form using spread.