The rest parameter syntax allows us to add any number of arguments as an array of a function. The last parameter can be prefixed with ... as a rest parameter. This will compose the rest of the provided parameters into a standard JavaScript array.
Example
const sumNumbers = (...params) => {
let summation = 0;
for (let num of params) {
summation += num;
}
return summation;
}
console.log( sumNumbers(28) ); // 28
console.log( sumNumbers(30, 40) ); // 70
Another Example
const getUserInfo = (name, gender, ...info) => {
return `User name: ${name}
Gender: ${gender}
Age: ${info[0]}
Status: ${info[1]}`;
}
let result = getUserInfo('Joe', 'M', '24', 'Active');
console.log(result);
// Output:
User name: Joe
Gender: M
Age: 24
Status: Active
The rest parameter should be at the end:
If we use the rest parameter at the beginning or in the middle of function parameters then it will throw an error. The rest parameter should be used at the end of The code will throw an error:
const sumNumbers = (...params, lastParam) => {
let summation = 0;
for (let num of params) {
summation += num;
}
return summation;
}
console.log( sumNumbers(28) ); // 28
console.log( sumNumbers(30, 40) ); // 70
// Uncaught SyntaxError: Rest parameter must be last formal parameter
Destructuring of rest parameters:
We can easily do the destructuring of the rest parameters. This destructuring of the rest parameter is only possible on the array. If we do destructuring then the data can be unpacked into distinct variables. See the destructuring assignment in the code segment below:
const getTotal = (...[math, english, chemistry]) => {
return math + english + chemistry;
}
const result = getTotal(83, 53, 60);
console.log(result);
// Output: 196
What’s the Difference Between Arguments and Rest Parameters?
Arguments can be assigned to a variable or passed into a function.
Rest parameters are only assigned an input value when called upon. When they return they leave their variable in their previous state (arguments must be assigned before they can work).
On a rest argument, for example, you may use the sort(), map(), forEach(), or pop() methods. You can’t, however, do the same with the arguments object.
Arguments cannot be passed into functions like rest parameters. Arguments are additional data, while rest parameters are used as input for other functions. Rest parameters will have inputs with specific names/contexts, but no outputs.
Instead of using the arguments object, it is better to use rest parameters, especially when writing ES6-compatible code.
Hope you had a good read!