Why Do You Need JavaScript Default Parameters?

Parameters and Arguments

Parameters represent a value you expect the function to receive; arguments are the values passed when calling the function. The concept is easy to understand, but it can be confusing in practice 😅. I usually remember them these way:

  • Parameter (placeholder): Parameter → Placeholder
  • Argument (actual value): Argument → Actual value
function example(parameter) {
// ...
}
example(argument);

Discovering the Problem

To understand default parameters, we need to start with existing problems. In JavaScript, functions can use any number of parameters and arguments, but if a parameter has no corresponding argument, it will become undefined.

function greeting(message) {
console.log(message);
}
greeting(); // undefined

Using Default Parameters

To use default parameter syntax, simply add an equals sign and a default value after the parameter. When no argument is provided, the default value will be used automatically.

function greeting(message = 'Default Greeting') {
console.log(message);
}
greeting(); // Default Greeting

If you do not use default parameters, you would need to write it like this:

function greeting(message) {
if (typeof message === 'undefined') {
message = 'Default Greeting';
}
console.log(message);
}
greeting(); // Default Greeting

References