Rest with Named Parameters
You'll learn how to combine named (regular) parameters with rest parameters to capture specific arguments while gathering the extras.
The Core Idea
When you use rest parameters in a function, you often want to capture some arguments individually by name first, then collect any remaining arguments with the rest operator. JavaScript allows this, but there's one crucial rule: named parameters must come before the rest parameter.
Think of it like a buffet line: you select specific dishes you know you want (named parameters), then pile everything else onto your plate (rest parameter).
How It Works
function makeProfile(name, age, ...hobbies) {
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Hobbies: ${hobbies.join(', ')}`);
}
makeProfile('Alice', 28, 'reading', 'hiking', 'coding');
// Name: Alice
// Age: 28
// Hobbies: reading, hiking, coding
Here, name and age are named parameters that capture the first two arguments specifically. The ...hobbies rest parameter then gathers everything else into an array.
Why Order Matters
The rest parameter acts as a "catch-all" for remaining arguments. If you tried to put it before named parameters, JavaScript wouldn't know where the rest ends and the named parameters begin:
// ❌ This won't work
function broken(...extras, name) { }
// SyntaxError: Rest parameter must be last formal parameter
When to Use This Pattern
This pattern shines when you have a few required or commonly-used arguments followed by optional, variable-length data—like building a logger with a message type and level, then capturing all additional details.
Key Takeaway: Always position named parameters before rest parameters to explicitly capture specific arguments first, then use rest to gather everything else.