What are default parameters and how are they used?
TL;DR
Default parameters supply a value when an argument is omitted or explicitly undefined; they do not apply to null, 0, false, or ''. The expression is evaluated at call time, so it can use earlier parameters and create a fresh object per call. Use defaults for genuine optional arguments, but validate values separately when null or another sentinel is invalid.
Default parameters
Default parameters, introduced in ECMAScript 2015 (ES6), supply a fallback when an argument is omitted or undefined.
Syntax
You can define default parameters by assigning a value to the parameter in the function definition. If no value or undefined is passed for that parameter, the default value will be used.
Example
Here is a simple example to illustrate how default parameters work:
In this example, the greet function has a default parameter name with a default value of 'Guest'. When the function is called without any arguments, it uses the default value. When an argument is provided, it overrides the default value.
Multiple default parameters
You can also define multiple default parameters in a function:
In this example, the createUser function has two default parameters: username and age. If no arguments are passed, both default values are used. If only one argument is passed, the second parameter uses its default value.
Using expressions as default values
You can also use expressions as default values for parameters:
In this example, the default value for b is an expression that depends on the value of a. If no arguments are passed, a is 0 and b is 1. If only a is passed, b is a + 1. If both a and b are passed, the provided values are used.
Common traps
Default parameters have their own parameter scope. A later parameter is unavailable to an earlier default, and referencing it before initialization throws a ReferenceError.
Further reading
- MDN Web Docs: Default parameters
- JavaScript.info: Default parameters
- ECMAScript 2015 (ES6) specification