EcmaScript 2015 introduced a new mechanism that enabled developers to define the default values of their function parameters.
Though it is powerful, that mechanism often cannot be used when setting the default values of the properties of received object arguments without destructuring them.
One such case would be a method having to pass the argument to another method :*
class A {
init(config) {
// handle config options speciifc to A
}
}
class B extends A {
init(config) { // destructuring here just isn't an option.
super.init(config);
// handle config options specific to B
}
}
* Could possibly be solved by this
As a result, developers tend to use the logical OR (||
) operator to assign a default value to these object arguments. Resulting in the following:
//...
init(config) {
super.init(config);
this.timeout = config.timeout || 4000;
}
//...
Very popular tools and libraries make use of the operator in that way
That operator works fine for most use cases but silently fails if a falsy value is a valid input.
In order to avoid introducing bugs, developers should check that the value is undefined rather than falsy. Unfortunately, doing so is much more verbose. Which is why developers still use the error-prone ||
operator to assign default values to this day.
Introduce a new operator, ??
, whose behavior is the following
DefaultExpression: LogicalORExpression ?? AssignmentExpression
- Let
lref
be the result of evaluatingLogicalORExpression
. - Let
lval
be?GetValue(lref)
. - If
lval
is notundefined
, returnlval
. - Let
rref
be the result of evaluatingAssignmentExpression
. - Return
?GetValue(rref)
.
TODO ??=
operator.
Default operator, works similarly to default parameters.
- Pro:
- It is similar to the null coalesce operator in other languages, closely resembles the current operator used to assign default values.
- Con:
- It does not have the exact same behavior as the other languages. This could make this operator slightly confusing to newcomers.
Formal, 4 years old, strawman
ESDiscuss thread about above strawman
Null coalesce operator ESDiscuss thread