What is the rest parameter in JavaScript?

Rest parameter ...

By adding a rest parameter to a function, we can send an n(0-Infinity) number of arguments as an array. The rest parameter is prefixed (by ...) and should always be the last argument of a function.

function testFn(...params) {
for(let i = 0,l = params.length; i < l; i++){
console.log(params[i]);
}
}
testFn(1,2,3,4,5);

Let’s create another function to calculate the sum of numbers.

function sum(...params) {
console.log(params);
let sum = params.reduce((acc,val)=>{
return acc + val;
},0);
return sum;
}
console.log("Calling sum(1,2)", sum(1,2));
console.log("Calling sum(1,2,3)", sum(1,2,3));
console.log("Calling sum(1,2,3,4)", sum(1,2,3,4));
console.log("Calling sum()", sum());

A single function can only have one rest parameter.

test(...prams1, ...params2, ...param3)

The rest parameter should be the last parameter of a function.

// wrong
test(prams1,...params2,param3);

test(prams1,params2,...param3);

Correct example

function multiple(multiplier, ... multiplicant) {
console.log(Array.isArray(multiplicant));
multiplicant.forEach(val=>{
console.log(`${val} * ${multiplier} = ${val* multiplier}`);
});
}
multiple(9, 1,2,3,4,5,6,7,8,9,10)

Rest parameter is an Array

The type of the rest parameter is Array.

function test(...restParam) {
    console.log(Array.isArray(restParam));
}
test();

Difference between function arguments object and rest parameter

  • The arguments object is not a real array, while rest parameters are Array.
  • The rest parameter only contains the extra parameters; whereas, arguments contain all the parameters passed to the function (this includes the rest parameter as an array).

Free Resources