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

JS Rest Parameters

Rest parameters let a function scoop up any number of extra inputs into one list, like a bag that grows to hold whatever you toss in. It is the same three dots, used the other way around.
Syntax
javascript
function functionName(first, ...rest) {
  // rest is an array of the remaining arguments
}

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.

उदाहरण: 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.

उदाहरण: Rest in Calculations

javascript
// Define the function `sum` taking `...numbers`
// Define the function `sum` taking `...numbers`
function sum(...numbers) {
  // Return `numbers.reduce((total, n) => total + n, 0)` from this function
  // Return `numbers.reduce((total, n) => total + n, 0)` from this function
  return numbers.reduce((total, n) => total + n, 0);
}
// Print `sum(1, 2, 3, 4)` to the console
// Print `sum(1, 2, 3, 4)` to the console
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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: Rest Rules

javascript
function log(first, ...rest) {
  console.log(first, rest);
}
log(1, 2, 3);
// function log(...rest, last) {} // SyntaxError: rest must be last
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

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.