Rest parameters
Collects the remaining function arguments into an array.
Available since: ES2015
Syntax
function name(...args) { … }Examples
Any number of arguments:
const sum = (...numbers) => numbers.reduce((total, n) => total + n, 0);
console.log(sum(1, 2, 3));
console.log(sum());Output:
6
0The first argument separately, the rest into an array:
function tag(label, ...items) {
return `${label}: ${items.join(', ')}`;
}
console.log(tag('Fruits', 'apple', 'pear'));Output:
Fruits: apple, pearNotes
The rest parameter must be the last one. It is a real array, unlike the old array-like arguments.
See also
- Spread syntax — Three dots spread an array or object into separate items.
- Destructuring assignment — Unpacks values from an array or object into separate variables.
- Default parameters — A parameter's value when no argument is passed.
In the tutorial
- Parameters — Function parameters and arguments in JavaScript — several parameters, order, missing arguments and default values.