← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 2 of 12

JS Rest Parameters

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

javascript
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

javascript
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

javascript
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

javascript
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

javascript
function log(first, ...rest) {
  console.log(first, rest);
}
log(1, 2, 3);
// function log(...rest, last) {} // SyntaxError: rest must be last

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.