Explain how the rest parameter works in JavaScript ES6. Provide an example of its usage in a function.
In : MCA Subject : Full Stack Web Development using MERNThe rest parameter is a feature introduced in ES6 (ECMAScript 2015) that allows a function to accept an indefinite number of arguments as an array.
- Only one rest parameter is allowed per function.
- The rest parameter must be the last parameter.
- It does not capture arguments if they are explicitly named.
Syntax :
function functionName(...restParameter) {
// restParameter is an actual array
}
Example :
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(5, 10, 15, 20)); // Output: 50
console.log(sum()); // Output: 0 (empty array)