TypeScript Nullish Coalescing Operator: Always Have a Fallback Value
A fallback value without null and undefined with the Nullish Coalescing operator
Nullish coalescing operator
Released in TypeScript 3.7 version, we have a new logical operator available. It’s called nullish coalescing and looks like this ??. But what does it do? To use it you need to have two values, one on the left and one on the right. In the middle, we use the ??.
If the value on the left of the operator is null or undefined, then the right-handed value will be used for a fallback. So by using this, you prevent having null or undefined values in your code. Sounds great, let’s take a look at the example below:
const var01 = null;const example01 = var01 ?? 'My other value';console.log(example01); // 'My other value'
example01 will result in My other value. Because the left-handed value is null, the right-handed value will be returned. The same situation applies with undefined. See the below example.
const var02 = undefined;const example02 = var02 ?? 'My other value';console.log(example02); // 'My other value'
For all other scenario’s which don’t include null or undefined as a value, it returns the left-handed value.
const var03 = 'Hello';
const var04 = true;const example03 = var03 ?? 'My other value';
const example04 = var04 ?? 'My other value';console.log(example03); // 'Hello'
console.log(example04); // true
OR logical operator (comparing)
The new nullish coalescing operator ?? is less strict than the OR || operator. The number zero 0, not a number NaN, or an empty string"" are allowed with ??. However, these values are falsy and not allowed with || which causes undesired behavior is certain situations. undefined and null are not allowed in both operators.
const var05 = 0;
const var06 = NaN;
const var07 = '';// Will return right-hand (restricts)
const example05 = var05 || 'My other value';
const example06 = var06 || 'My other value';
const example07 = var07 || 'My other value';// Will return left-hand (allows)
const example08 = var05 ?? 'My other value';
const example09 = var06 ?? 'My other value';
const example10 = var07 ?? 'My other value';
Note: using
||and??together will give aSyntaxError.

