Nullish Coalescing

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.

true || 1;
// true

2 || 1;
// 2

false || 1;
// 1

undefined || 1;
// 1

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.

function defaultNumber(num: number | undefined): number {
    return num || -1;
}

defaultNumber(3);
// 3

defaultNumber(undefined);
// -1

defaultNumber(0);
// -1

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.

function defaultNumber(num: number | undefined): number {
    return num ?? -1;
}

defaultNumber(3);
// 3

defaultNumber(undefined);
// -1

defaultNumber(0);
// 0

Now, the expected result of 0 is returned.