JavaScript Rest Parameter

JavaScript rest parameter denoted by three dots (…) is used to represent an indefinite number of arguments as an array. A function can be called with any number of arguments, regardless of how it was defined.

Syntax

function f(x, y, ...args) {
  // ...
}

One thing to remember is that only the last parameter can be a Rest Parameter.

Visual Representation

Visual Representation of How to Use the rest parameter

Example 1: How to Use the rest parameter

function multiplication(...args) {
 return args.reduce((accumulator, current) => accumulator * current);
};

console.log(multiplication(1, 3, 5, 7, 9));

Output

945

Example 2: Passing other arguments

function func (a, b, ...manyMoreArgs) {
 console.log(a); 
 console.log(b);
 console.log('manyMoreArgs', manyMoreArgs); 
 console.log(manyMoreArgs[0]);
 console.log(manyMoreArgs.indexOf('wolves'));
 console.log(manyMoreArgs.length);
};

func('mia', 'despacito', 'attention', 'wolves', 'sorry');

Output

mia
despacito
manyMoreArgs [ 'attention', 'wolves', 'sorry' ]
attention
1
3

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.