Rest parameters allow a function to accept an indefinite number of arguments as an array.
This is cleaner than using the arguments object from ES5.

1. Basic Syntax

function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}console.log(sum(1, 2, 3)); // 6
console.log(sum(5, 10, 15, 20)); // 50
  • …numbers collects all remaining arguments into an array.
  • Must be the last parameter in the function definition.

2. Rest Parameters vs arguments

ES5:

function sum() {
let total = 0;
for(let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}

ES6 (Rest Parameters):

function sum(...args) {
return args.reduce((a, b) => a + b, 0);
}

Advantages of Rest Parameters:

  • True Array (can use array methods like map, filter, reduce)
  • More readable and concise
  • Works only for rest of arguments; named parameters are easier to handle

3. Rest Parameters with Named Parameters

You can mix normal parameters and rest parameters:

function greet(greeting, ...names) {
console.log(greeting + " " + names.join(", "));
}
greet("Hello", "Alice", "Bob", "Zaman");
// Hello Alice, Bob, Zaman
  • greeting is a normal parameter
  • …names collects the rest
  • ⚠️ Rest parameter must always be last:
function wrong(...args, last) { } // ❌ SyntaxError

4. Using Rest Parameters with Arrays

Rest parameters can be combined with spread operator:

<const nums = [1, 2, 3];
function printNumbers(...numbers) {
console.log(numbers);
}
printNumbers(...nums); // [1, 2, 3]
  • …nums spreads array into individual arguments
  • …numbers collects them back into an array

5. Rest Parameters with Destructuring

function show([first, second, ...rest]) {
console.log(first, second, rest);
}
show([1,2,3,4,5]); // 1 2 [3,4,5]
  • Works with arrays and objects (with nested destructuring)

6. Rest Parameters in Arrow Functions

const sum = (...nums) => nums.reduce((a,b) => a+b, 0);

console.log(sum(5,10,15)); // 30
  • Clean, modern ES6 syntax

Categorized in:

Javascript ES6,