46. Rest Parameters (...args)
The Rest Parameter syntax (...) allows a function to accept an indefinite number of arguments as an array. It must be the last parameter in the function definition.
Syntax and Usage
javascript function sumAll(...numbers) { console.log(typeof numbers); // Output: 'object' (it's an array)
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
console.log(sumAll(1, 2)); // Output: 3 console.log(sumAll(10, 20, 30)); // Output: 60 console.log(sumAll()); // Output: 0
Combining Rest and Normal Parameters
You can combine rest parameters with regular parameters, but the rest parameter must always be last.
javascript
function logUserActions(user, ...actions) {
console.log(${user} performed ${actions.length} actions.);
console.log('Actions:', actions);
}
logUserActions('Manager', 'login', 'edit', 'delete'); // user = 'Manager' // actions = ['login', 'edit', 'delete']