The null coalescing operator has been a long requested feature in TypeScript. Indeed, when I began using TypeScript a few years ago, I assumed it was available and was suprised to find this wasn't the case.
Null coalescing remained unsupported until recently because the TypeScript team (rightly) wanted to mantain compatibility with any eventual TC39 decisions regarding implementation and semantics.
const a = b || c;
While this appears to achieve the same end (and in many cases, will) the logical OR operator (
||) applies for any falsy value i.e.
const b = 0; const c = 42; const a = b || c; console.log(a); // 42
The null coalescing operator (
??) is more strict; it only applies where the value is
const b = 0; const c = 42; const a = b ?? c; console.log(a); // 0
This additional strictness can be useful in scenarios where subtle errors may otherwise be introduced due to unintended falsy evaluation i.e. where
"" are valid values in your application data or state.