Rest parameters

Rest parameter is a new and improved way to accept any number of arguments in a function. It is represented by three dots (…) followed by rest parameter name, for example …restArgs.

In JavaScript functions, any number of arguments can be passed. The rest parameter will gather them all in a single array. So the rest parameter is an array which contains rest of the arguments.

Without using rest parameter the function will look like this:

function addMe(a, b, c) {
   return a + b + c
}

console.log(addMe(10, 20, 30)) //60

console.log(addMe(10, 20, 30, 40, 50, 60)) //60 ignores extra arguments

Although it will not throw an error for passing more number of arguments (than number of parameters passed in the function defination), it is not going to give expected outout for more number of arguments .

In such situation rest parameter comes to the rescue.

Syntax:

function f(...restArgs)
function f(arg1, ...restArgs) { // function body }
function f(arg1, arg2, ...restArgs) { // function body}

Example:

function restTesting(...restArgs) {
   for(const el of restArgs) {
      console.log(`Hello ${el} !`) 
    }
}

restTesting('John') 
// "Hello John !"

restTesting('John', 'Smith') 
//"Hello John !" 
//"Hello Smith !"

restTesting('John', 'Smith', 'Marry') //  
//"Hello John !"
//"Hello Smith !"
//"Hello Marry !"

Originally ECMAScript 4 introduced rest parameters but it was standardized only in ECMAScript 6.

Rest parameters are arrays. All array method like sort(), map(), forEach() etc. can be used with rest parameters.

Example:

function mapping(...restArg) {
   return restArgs.map(el => el * 2)
}

console.log(mapping(1, 2, 3, 4)) // [2, 4, 6, 8]

While using rest parameters few things must keep in mind.

  • There can be only one rest parameter in a function.

Example:

function checkRest(arg1, ...restFirst, ....restSecond) { //function body } //throws an error
  • The rest parameter must be at last.

Example:

function checkRest(arg1, ...restArgs, argN) { //function body } //throws an error
  • The rest parameter can not be used as a setter in object literal.

Example:

const person = {
   set PersonName(...fullNameList) {
   // some code
   }
}

The above code throws an error because the object literal setter accepts only single argument while rest parameter is an array of infinite arguments.

arguments object and rest parameters are different

Before introduction of rest parameters, JavaScript was using arguments object (you will find it in old code). Even it stores all arguments index-wise, arguments is not a pure array. We can not use array methods like map(), sort() forEach() etc. with arguments.

Note: Even arguments is not pure array it has a length property.

Example:

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

console.log(sum(1, 2)) // 3

console.log(sum(1, 2, 5)) // 8

However arguments can be converted in to an array like this:

let arr = Array.prototype.slice.call(arguments) // using prototype 

let arr = Array.from(arguments) //Using Array.from() method

let arr = [...arguments] //using spread operator

Rest parameter in Function constructor

Function constructor allows to create function dynamically. Function constructor can be created using rest parameters.

Example:

const add = new Function("a", "b", "return a+b") // using regular arguments

console.log(add(100, 200)) //300

const restAdd = new Function("...restArg", "return restArg.reduce((acc, cur) => acc + cur, 0)")

console.log(restAdd(10, 20, 30, 40, 50)) // 150

Summary

Rest parameters are useful when argument size is not fixed.

Rest parameters are functional parameter having syntax with three dots(…) followed by parameter name.

Rest parameters must be the last parameter.

Rest parameters are arrays. All the array methods can be used with rest parameters.

Subscribe
Notify of

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

[…] operator works exactly opposite to rest parameters. Rest parameters collects the functional parameters in an array while spread operator splits the […]