Suppose a function needs one required value and an unknown number of extras. A rest parameter collects those extras without making you convert the `arguments` object into an array. section 15.3
Put `...` before the final parameter name: `function family(spouse, ...kids)`. The first argument binds to `spouse`; every remaining argument goes into the `kids` array. A function may have only one rest parameter, and it must come last. Putting another parameter after it is a syntax error. section 15.3 section 15.5
function countKids(...allMyChildren) {
return `You have ${allMyChildren.length} children!`;
}
countKids('Talan', 'Jonathan'); 1
function family(spouse, ...kids) {
return `You are married to ${spouse} with ${kids.length} kids`;
}
family('Christina', 'Talan', 'Jonathan'); 2
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":4,\"ch\":53},{\"line\":4,\"ch\":54}],[{\"line\":10,\"ch\":53},{\"line\":10,\"ch\":54}]]"}
!@%STYLE%@!
Compare collecting every argument with collecting only those after a named parameter. In `family('Christina', 'Talan', 'Jonathan')`, `kids.length` is 2. section 15.3
Rest also makes variable-property helpers easier to read. In `pluck(object, ...props)`, the object stays separate while the requested property names form an array that `map` can process. The earlier approach built that array with `Array.from(arguments).slice(1)`. section 15.0 section 15.3
function pluck(object, ...props) {
return props.map(function(property) {
return object[property];
});
}
The first argument supplies the object; `props` holds the remaining property names for the `map` call. section 15.3
A rest parameter is useful in a wrapper, too. Gather the wrapper’s arguments with `...args`, run extra logic such as logging, then pass the array to the original function with `apply`. That preserves the arguments the caller supplied. section 15.4
Listing 15.8. Using rest to forward parameters when monkey-patching
The image-processing wrapper saves the original method, logs the collected arguments, and returns the original method’s result. section 15.4
Try it
Write `cssClass(primary, ...others)` so `cssClass('button', 'danger', 'medium')` returns `"button button-danger button-medium"`. Start the list with `primary`, add each prefixed extra, then join with spaces. section 15.3


