Default & Rest
Parameters
Master two essential JavaScript features that make your functions flexible, resilient, and ready for any number of arguments.
What Are Parameters?
Every function you write can accept inputs called parameters. They act as placeholders that receive arguments when the function is called. But what happens when an argument is missing or you don't know how many will arrive?
Introducing Default Parameters
A default parameter lets you assign a fallback value right in the function signature. If the caller omits that argument (or passes undefined), the default kicks in automatically.
Introducing Rest Parameters
A rest parameter collects all remaining arguments into a real Array. It uses the ... (spread/rest) syntax and must always be the last parameter.
How Default Values Resolve
How Rest Collects Arguments
The Formal Rules
Rest vs arguments Object
| ...rest | arguments | |
|---|---|---|
| Type | True Array | Array-like object |
| Array methods | ✓ .map(), .filter(), etc. | ✕ Must convert first |
| Arrow functions | ✓ Works everywhere | ✕ Not available |
| Named params | ✓ Collects only extras | Contains all arguments |
| Readability | Explicit intent | Hidden / implicit |
How to Apply These Features
Example 1: Default in Action
Example 2: Rest in Action
Example 3: Combining Both
Defaults Can Be Expressions
Default values aren't limited to simple literals. You can use function calls, other parameters, and expressions as defaults. They evaluate left to right at call time.
Common Mistakes to Avoid
Summary Comparison
| Default Parameters | Rest Parameters | |
|---|---|---|
| Syntax | param = value | ...param |
| Purpose | Fallback for missing args | Collect extra args |
| Position | Any position (best at end) | Must be last |
| Result type | Single value | Array |
| Trigger | undefined / omitted | Always active |
| Count allowed | Multiple defaults OK | Only one per function |
Question 1 of 5
What is the output of the following code?
Question 2 of 5
Which placement of a rest parameter is valid?
Question 3 of 5
What is the output?
Question 4 of 5
What is the output?
Question 5 of 5
What does typeof rest return inside a function declared as function f(...rest) {}?