Rest Parameters
EasyIn plain terms
Rest parameters ...args collect all remaining arguments into an array. Must be the last parameter. Replaces the need for the arguments object. Works with arrow functions.
What you need to know
- •...args collects rest
- •Must be last param
- •Real array (unlike arguments)
Try it yourself
Copy the code below and run it in your browser console or a code editor:
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
function log(first, ...rest) {
console.log('First:', first);
console.log('Rest:', rest);
}
log('a', 'b', 'c'); // First: a, Rest: ['b', 'c']
const multiply = (mul, ...nums) =>
nums.map(n => n * mul);
multiply(2, 1, 2, 3); // [2, 4, 6]Learn more
Dive deeper with these trusted resources: