Rest Parameters
Rest Parameters
Section titled “Rest Parameters”Introduction
Section titled “Introduction”Rest parameters (...) allow a function to accept an indefinite number of arguments as an array. They replaced the older arguments object in modern JavaScript.
Syntax
Section titled “Syntax”function sum(...numbers) { return numbers.reduce((total, n) => total + n, 0);}Example
Section titled “Example”function logAll(...args) { args.forEach(arg => console.log(arg));}
logAll(1, 2, 3, 4); // logs 1, 2, 3, 4With Named Parameters
Section titled “With Named Parameters”function greet(greeting, ...names) { return names.map(name => `${greeting}, ${name}!`);}
console.log(greet('Hello', 'Alice', 'Bob', 'Charlie'));// ['Hello, Alice!', 'Hello, Bob!', 'Hello, Charlie!']Rest vs arguments
Section titled “Rest vs arguments”// arguments — array-like, not a real arrayfunction oldWay() { const args = Array.from(arguments); // must convert}
// rest — real arrayfunction newWay(...args) { // args is a real array args.map, args.filter, args.reduce all work}Summary
Section titled “Summary”...paramscollects all remaining arguments into an array- Must be the last parameter
- It’s a real Array (unlike
arguments) - Cleaner, modern alternative to
arguments