Sub topic 6
Rest Parameters in Functions
This chapter assumes you can write regular and arrow functions and that you have seen rest elements in array patterns in the previous chapter. A rest parameter uses the same ... syntax in a function's parameter list. It gathers any number of arguments into a single array.
The working model
When you prefix the last parameter with ..., JavaScript binds the named parameters first, by position. Every argument left over goes into a new array. If nothing is left over, the array is empty. It is never undefined.
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum()); // 0 (nums is [])Named parameters and a rest parameter can be combined. The named ones take the first arguments:
function log(level, ...messages) {
console.log(`[${level}]`, messages.join(' '));
}
log('info', 'server', 'started'); // [info] server started
log('warn'); // [warn]Rest parameters vs `arguments`
Older code reads extra arguments from the arguments object. A rest parameter is a better choice in three ways:
| Feature | `...rest` | `arguments` |
|---|---|---|
| Real array with `map`, `filter`, `reduce` | Yes | No, it is array-like only |
| Available in arrow functions | Yes | No, an arrow sees the outer function's `arguments` |
| Contains only the extra arguments | Yes | No, it contains all of them |
const max = (...values) => values.length ? Math.max.apply(null, values) : null;
console.log(max(4, 11, 7)); // 11
console.log(max()); // nullCommon errors
The rest parameter must come last, and a function can have only one. Each of the following is a SyntaxError:
// function bad1(...items, last) {} // rest must be last
// function bad2(...a, ...b) {} // only one rest parameter
// function bad3(...items = []) {} // rest cannot have a default
// function bad4(...items,) {} // no trailing comma after restA rest parameter cannot take a default because it already defaults to an empty array.
function f(a, b, ...rest) {}
console.log(f.length); // 2Rest and destructuring together
The rest parameter is an ordinary array binding, so you can destructure it directly in the parameter list:
function firstTwo(...[a, b]) {
return [a, b];
}
console.log(firstTwo(10, 20, 30)); // [10, 20]This is legal, but it is rarely clearer than naming the parameters a and b. Use it only when you also need the array.
When to reach for rest
Use a rest parameter when the number of arguments really varies, as in sum, log, or a wrapper that forwards its arguments to another function. For a fixed set of optional settings, an options object is clearer. A later chapter covers that approach.
Exercise
What does this print, and why? function tag(name, ...attrs) { return attrs.length; } console.log(tag('div'), tag.length);
Show answer
It prints 0 1. With only one argument, attrs is an empty array, so its length is 0. tag.length counts only the named parameters before the rest parameter, which here is just name.
Exercise
Rewrite function avg() { const nums = Array.prototype.slice.call(arguments); return nums.reduce((t, n) => t + n, 0) / nums.length; } as an arrow function.
Show answer
const avg = (...nums) => nums.reduce((t, n) => t + n, 0) / nums.length; The rest parameter gives you a real array, so you no longer need to convert arguments, and arrow functions have no arguments object of their own.