Rest Parameter with Function Parameters

Rest Parameter with Function Parameters

The rest parameter for function parameters was introduced in ES6 to help us create more flexible functions. The rest parameter syntax allows a function to accept an indefinite number of arguments. These arguments are stored in an array that can be accessed later from inside the function.

Check out this code:

function howMany(...args) {
  return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2));
//3 arguments passed
console.log(howMany("string", null, [1, 2, 3], { }));
//4 arguments passed

The console would display the strings 3 arguments passed and 4 arguments passed.

The rest parameter eliminates the need to check the args array and allows us to apply map(), filter() and reduce() on the parameters array.

Check out another example where function sum is able to take any number of arguments and return their sum.

const sum = (...args) => {
    return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3))  // returns 6
console.log(sum(12, 43, 76))  //return 131

Read more about rest parameter in MDN docs