??. In this article we will take a look at what it does and where it can be used.
|| is used to set a default value for a variable as can be seen below.
const myGreeting = greeting || 'Hello!';
However, using the OR operator for this purpose can actually have unintended consequences as it will fall back to the default value whenever the variable evaluates to something falsy. Let's take a look at an example in which we are setting the default value for a number.
const myNumber = number || 12;
number = 15 then the code above would evaluate such that
myNumber = 15. If
number = null then it will use the default resulting in
myNumber = 12.
So far so good but what if we set
number = 0 ? We'd run into trouble because although
number has a value it's a value that when evaluated as boolean is equivalent to
false so we'd wind up falling back to our default
number = 12.
This is where the Nullish Coalescing Operator can come in very handy by switching out
?? we can guarantee the default value will only be used when
number = null or
number = undefined.
const myNumber = number ?? 12;