JS Rest Parameters
In this page:
What Are Rest Parameters
Rest parameters use the same ... syntax as spread but in the opposite direction, collecting any number of remaining function arguments into a single real array inside the function.
Example: What Are Rest Parameters
function showArgs(...args) {
console.log(args); // a real array
}
showArgs(1, 2, 3);
Rest in Calculations
A common use is writing a function like sum(...numbers) that accepts any number of arguments and reduces them together, without needing to know in advance how many values will be passed.
Example: Rest in Calculations
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4));
Rest and Array Destructuring
When destructuring an array, a rest element like [first, ...rest] captures the first value separately and gathers everything remaining into a new array called rest, which is handy for splitting a head element from the rest of a list.
Example: Rest and Array Destructuring
const [first, ...rest] = [1, 2, 3, 4];
console.log(first, rest);
Rest and Object Destructuring
The same pattern works when destructuring an object, where {id, ...details} pulls out id by itself and collects every other property into a new details object, useful for separating one key field from the rest of a record.
Example: Rest and Object Destructuring
const { id, ...details } = { id: 1, name: "Sam", age: 30 };
console.log(id, details);
Rest Rules
A rest parameter must be the last parameter in a function's parameter list, since JavaScript needs to know where the fixed parameters end and the open-ended collection begins.
Example: Rest Rules
function log(first, ...rest) {
console.log(first, rest);
}
log(1, 2, 3);
// function log(...rest, last) {} // SyntaxError: rest must be last
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: