Use Default Parameters
Default parameters allow providing default values for function parameters. These default values are used if nothing or undefined
is passed into the function. For example, function f(p = 42) { ... }
sets p
to 42
if no value is passed in.
Previous ways of setting default values, for example p = p || 42
can be converted to default parameters. This refactoring supports converting the following expressions and variants of them:
- or assignment, e.g.
p = p || 42
orp ||= 42
- nullish coalescing operator, e.g.
p = p ?? 42
- ternary with falsy check on parameter, e.g.
p = p ? p : 42
- ternary with
null
check, e.g.p = p == null ? 42 : p
orp = p != null ? p : 42
- ternary with
undefined
check, e.g.p = p === undefined ? 42 : p
- ternary with
typeof
check, e.g.p = typeof p === "undefined" ? 42 : p
Learn More: Default Parameters (MDN)
This refactoring can change the semantics of your code in some cases.
Default values are only used in place of undefined
.
The code that is replaced by this refactoring may have provided defaults for falsy or null
values as well.
This may lead to undesired behavior, for example:
function example(x) {
x = x == null ? "default" : x;
console.log(x);
}
example(null); // prints "default"
becomes
function example(x = "default") {
console.log(x);
}
example(null); // prints "null"
Original Code
Changes
1 | function x(p) { | |
2 | p = p || 42; | |
1 | function x(p = 42) { | |
3 | 2 | console.log(p); |
4 | 3 | } |
Transformed Code
function x(p = 42) {
console.log(p);
}