What are Rest Parameters?
Rest parameters allow a function to accept an indefinite number of arguments as an array. They'redenoted by three dots (...) followed by a parameter name.
Rest parameters are useful when you want a function to work with any number of arguments, replacing the need for the 'arguments' object.
Basic Rest Parameters
// Function accepts any number of arguments
function sum(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(sum()); // 0
console.log(sum(5)); // 5
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
// Rest parameters create an actual array
function printArgs(...args) {
console.log(args);
console.log(Array.isArray(args)); // true
console.log(args.length);
}
printArgs(1, 2, 3);
// [1, 2, 3]
// true
// 3Rest parameters collect arguments into an array, making it easy to work with variable argument counts.