Default Parameters

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

Illustration of default_parameters
Illustration of default_parameters

💡 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

JAVASCRIPT
function greet(name = 'Guest') {
  console.log('Hello, ' + name + '!');
}

greet();         // Hello, Guest!
greet('Alice');  // Hello, Alice!
Output
Hello, Guest!
Hello, Alice!

Key points:

  • If the argument is undefined or missing, the default value is used.
  • If null or any other value is passed, that value is used instead.
Behavior Comparison: Default Parameter vs No Default
Function CallWithout DefaultWith Default
func()param = undefinedparam set to default
func(undefined)param = undefinedparam set to default
func(null)param = nullparam = 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

JAVASCRIPT
function randomNumber(max = Math.floor(Math.random() * 100)) {
  console.log(max);
}

randomNumber();    // Prints a random number between 0 and 99
randomNumber(50);  // Prints 50
Output
e.g. 27
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

JAVASCRIPT
function multiply(a, b = a) {
  return a * b;
}

console.log(multiply(5));    // 25 (b defaults to 5)
console.log(multiply(5, 2)); // 10
Output
25
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 null or other falsy values except undefined.