What is rest parameter? explain with example

What is rest parameter?

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 rest of the provided parameters into a standard JavaScript array.

Example of rest parameter

var sumNumbers = function(...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:

function getUserInfo(name, sex, ...info){
    return `User name: ${name}
            Gender: ${sex}
            Age: ${info[0]}
            Status: ${info[1]}`;
}

var 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 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:

var sumNumbers = function(...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 rest parameter is only possible on array. If we do destructuring then the data can be unpacked into distinct variables. See the destructuring assignment in the code segment below:

 
function getTotal(...[math, english, chemistry]) {
  return math + english + chemistry;
}

var result = getTotal(83, 53, 60);
console.log(result);
// Output: 196
Share