Combining Regular and Rest Parameters
What you'll learn: How to mix named parameters with a rest parameter so your function can handle both required and optional arguments in one clean signature.
The Core Idea
You can define a function with one or more regular (named) parameters followed by a single rest parameter. This lets you capture specific values by name while collecting any extras into an array. Think of it like a restaurant order form: you might have required fields for "table number" and "main dish," but also a catch-all section for "additional requests."
How It Works
The regular parameters come first and capture arguments by position. The rest parameter (always last) sweeps up everything left over:
function greet(greeting, ...names) {
return `${greeting} to ${names.join(", ")}!`;
}
console.log(greet("Hello", "Alice")); // "Hello to Alice!"
console.log(greet("Welcome", "Bob", "Carol")); // "Welcome to Bob, Carol!"
Here, greeting is a required parameter, and names collects all remaining arguments into an array.
Practical Example
function logEntry(level, timestamp, ...messages) {
console.log(`[${level}] ${timestamp}`);
messages.forEach(msg => console.log(` - ${msg}`));
}
logEntry("ERROR", "2024-01-15", "Database connection failed", "Retrying...");
// [ERROR] 2024-01-15
// - Database connection failed
// - Retrying...
The first two arguments fill level and timestamp, while everything else becomes the messages array.
Key Takeaway: Combining regular and rest parameters gives you the best of both worlds—required named inputs plus flexible handling of variable arguments—making your functions both clear and adaptable.