DEV Community

loading...
Cover image for Rest Parameters

Rest Parameters

zaidakhterr profile image Zaid Akhter 惻Updated on 惻2 min read

Rest parameters are a feature introduced in ES6. They allow us to represent any indefinite number of arguments in a function as an Array.

To use this new syntax, you can simply prefix the parameter with ... and this will create an array with all the user supplied arguments. In the restDemo function below I simply return the parameters:

const restDemo = (...parameters) => {
  return parameters;
};

console.log(restDemo(2, 3));
// expected output: [2,3]

console.log(restDemo(1, 2, 3, 4, 5));
// expected output: [1,2,3,4,5]

console.log(restDemo('hi'));
// expected output: ['hi']
// Rest parameters will put even a single element into an array

console.log(restDemo());
// expected output: []
// If no elements are passed it is defined as an empty array

Now, lets consider a simple use case for rest parameters. The add function below takes any number or arguments as input and returns their sum. I am using ES6 array method reduce here to add the values.

const add = (...numbers) => {
  return numbers.reduce((n, sum) => (sum += n), 0);
};

console.log(add(2, 3));
// expected output: 5

console.log(add(1, 2, 3, 4, 5));
// expected output: 15

Also, an important thing to note is that rest parameters can only be applied to the very last argument of a function. Consider some functions as below, the firstFunction passes the second parameter b as a rest parameter. This will throw an error.

const firstFunction=(a,...b,c)=>{
  // some code
  // this will throw an error
}

While the secondFunction passes the third(and last) parameter c as a rest parameter. This will put all the parameters after the first two into an array.
If only two parameters are passed c will be defined as an empty array.

const secondFunction=(a,b,...c)=>{
  // some code
}

// Examples
secondFunction(1,2) // a=1, b=2 ,c=[]

secondFunction(1,2,3,4) // a=1, b=2 ,c=[3,4]

Discussion (0)

Forem Open with the Forem app