Variadic calculations
A function must accept a variable number of numeric inputs.
JS Puzzles · Const
Rest parameters let a function accept any number of arguments by gathering the remaining arguments into an array. They are written with ... before the final parameter name.
A rest parameter is written as three dots before the final parameter name in a function declaration. When the function runs, any arguments not assigned to earlier named parameters are collected into that parameter as a real array, so array methods can be used directly.
function name(...rest) { /* body */ }| Name | Type | Description |
|---|---|---|
args | parameters | Named parameters before the rest parameter receive their corresponding arguments. |
...rest | array | The final rest parameter receives all remaining arguments in an array. |
The page does not specify a general return value; the function's own return statement determines its result.
... depends on its position: at the end of a function parameter list, it is rest syntax.function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(2, 4, 6)); // 12The rest parameter gathers all arguments after the function's named parameters into an array.
A function must accept a variable number of numeric inputs.
A wrapper forwards an arbitrary number of arguments to another function.
A utility needs direct access to array methods while processing extra inputs.
spread syntaxargumentsfunction parameters