In JavaScript, default parameters allow you to initialize function parameters with default values if no argument or undefined is passed.

💡 Why Use Default Parameters?
They help avoid errors from missing arguments and simplify function calls by providing fallback values.
Syntax:
📌 Deep Dive: Basic Default Parameter
function greet(name = 'Guest') {
console.log('Hello, ' + name + '!');
}
greet(); // Hello, Guest!
greet('Alice'); // Hello, Alice!
Hello, Alice!
Key points:
- If the argument is
undefinedor missing, the default value is used. - If
nullor any other value is passed, that value is used instead.
| Function Call | Without Default | With Default |
|---|---|---|
func() | param = undefined | param set to default |
func(undefined) | param = undefined | param set to default |
func(null) | param = null | param = null (default ignored) |
💡 Default Parameters Can Use Expressions
Default values can be any valid expression, including function calls or calculations.
📌 Deep Dive: Expression as Default
function randomNumber(max = Math.floor(Math.random() * 100)) {
console.log(max);
}
randomNumber(); // Prints a random number between 0 and 99
randomNumber(50); // Prints 50
50
⚠️ Important: Default Parameters Are Evaluated at Call Time
The default expression is re-evaluated every time the function is called without that argument.
Default parameters can also reference parameters declared before them:
📌 Deep Dive: Default Parameter Using Previous Parameter
function multiply(a, b = a) {
return a * b;
}
console.log(multiply(5)); // 25 (b defaults to 5)
console.log(multiply(5, 2)); // 10
10
💡 Summary
- Use default parameters to handle missing or undefined arguments gracefully.
- Defaults can be literals, expressions, or depend on earlier parameters.
- Defaults do not replace
nullor other falsy values exceptundefined.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What happens if you call a function with a default parameter but pass undefined explicitly?
Question 2 of 2
Which of the following will NOT trigger the default parameter to be used?
Loading results...