ES2020 brings the nullish coalescing operator to JavaScript, which allows us to create default values succinctly. The nullish coalescing operator is created with two question marks (??
) and allows us to perform a logical OR only when the left value is null
or undefined
. For example:
const issueStatus = selectedStatus ?? 'open';
If selectedStatus
is 'closed'
(a truthy value), the issueStatus
constant will be assigned 'closed'
. If selectedStatus
is undefined
or null
(which are falsey), the issueStatus
constant will be assigned 'open'
.
Now you might be wondering, why not use the logical OR operator (||
)? For example:
const issueStatus = selectedStatus || 'open';
The difference here is that zero and an empty string are considered falsey, so if selectedStatus
is either of those values, issueStatus
will get assigned 'open'
. With the nullish coalescing operator, the right side will only be evaluated if the left side is undefined
or null
. I've definitely been bitten by bugs where I intended for zero to be assigned as opposed to the default value in a logical OR expression.