Collect Extra Arguments
Rest parameters gather remaining arguments into an array.
They are useful when you do not know how many inputs you will receive.
JavaScript Tutorial
Rest parameters collect extra function arguments into an array.
They make functions flexible when input count varies.
Many utilities accept an unknown number of inputs. Rest parameters handle those cases cleanly.
They are clearer and safer than the old arguments object.
function name(...rest) { ... }function sum(...nums) {
return nums.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3));Collect all arguments into an array and reduce.
function log(level, ...messages) {
console.log(level, messages);
}
log("info", "start", "loading");Use rest after fixed parameters.
Rest parameters gather remaining arguments into an array.
They are useful when you do not know how many inputs you will receive.
The rest parameter must be the last parameter.
Only one rest parameter is allowed.
Rest parameters are clearer than the old arguments object.
They work in arrow functions too.
function wrap(fn, ...args) {
return fn(...args);
}
console.log(wrap(Math.max, 3, 9, 2));Combine rest and spread to forward arguments.
const join = (...parts) => parts.join("-");
console.log(join("a", "b", "c"));Rest parameters work in arrow functions.
Without
function sum() {
return Array.from(arguments).reduce((a, b) => a + b, 0);
}With
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}Rest must be the last parameter.
Arrow functions do not have arguments; use rest.
Rest can be an empty array if no extra args are passed.
It collects all remaining arguments, so it must be at the end.
Yes, rest works with arrow functions.
Rest collects into an array; spread expands an array.
Practice: Write a function that multiplies all numbers passed in.
// TODO: function multiply(...nums)
One Possible Solution
function multiply(...nums) {
return nums.reduce((acc, n) => acc * n, 1);
}
console.log(multiply(2, 3, 4));It collects remaining arguments into an array.
No, only one is allowed and it must be last.
Rest collects arguments, spread expands them.
Try passing different counts of numbers.