Variadic functions
A function needs to accept an arbitrary number of arguments and process them as an array.
JS Puzzles · Const
Rest parameters gather remaining function arguments into an array, while spread syntax expands an iterable into separate arguments or elements. Both use ..., but their syntactic position determines which behavior applies.
The same three-dot notation has opposite roles depending on where it appears: in a function parameter list, rest gathers remaining arguments into an array; in a call or similar expression, spread expands an iterable into separate arguments or elements.
function name(required, ...rest) {}
name(...iterable)| Name | Type | Description |
|---|---|---|
rest | Array | The parameter name after ...; it receives the remaining arguments as an array. |
A rest parameter produces an array containing the remaining arguments; spread syntax supplies iterable items as arguments or literal elements.
... gathers the remaining supplied arguments into an array....name identifies a rest parameter.function collect(first, ...rest) {
return [first, ...rest];
}
const values = collect("a", "b", "c");
console.log(values); // ["a", "b", "c"]
console.log(Math.max(...values.map(value => value.length))); // 1The function gathers extra arguments into an array, while the later call expands an iterable into individual arguments.
A function needs to accept an arbitrary number of arguments and process them as an array.
An existing array must provide individual arguments to a function call.
Values from an iterable need to be inserted into an array or combined with other literal elements.
Rest parameters appear in a function definition and collect all remaining arguments into an array. Spread syntax appears in a call or similar expression and expands an iterable into separate arguments or elements.
Follow-up: What happens if a rest parameter is followed by another parameter? It is invalid because the rest parameter must be last.
A rest parameter lets one function accept any number of arguments while providing those extra values as a real array. This is more convenient for array operations than an array-like argument collection.
Follow-up: How would you pass the collected values to another function expecting separate arguments? Use spread syntax at the call site, such as target(...values).
Spread syntax expands an iterable in a function call, so an array can supply individual arguments to a function such as Math.max. The same notation can also expand values into array or object literals as documented on the page.
Follow-up: What determines whether ... gathers or expands? Its syntactic position: parameter-list position means rest, while call or similar expression position means spread.
argumentsfor..ofiterable objectsArray