Nullish Coalescing
CodeTypeScript
The nullish coalescing operator ?? is an alternative to the boolean check ||. They perform similar functions but are importantly distinct.
The || operator uses a false check, and will return the right-side of the expression if the left-side is falsy.
This is a useful way to provide defaults, but can come with issues because of the use of a falsy condition. The following example shows this. For the last example, we expect the return value to be 0, but it ends up being -1 because 0 is falsy.
To correct this, you can use the nullish coalescing operator. This operator will return the right-side of the expression if the left-side is either null or undefined.
Now, the expected result of 0 is returned.