Search⌘ K

Nullish Coalescing and Null or Undefined Operands

Explore how to use the nullish coalescing operator in TypeScript to provide default values for variables that may be null or undefined. Understand how TypeScript checks for null or undefined operands in arithmetic operations and how the nullish coalescing operator can prevent errors in these cases.

Nullish coalescing

In general, it is a good idea to check that a particular variable is not either null or undefined before using it, as this can lead to errors. TypeScript allows us to use a feature of the 2020 JavaScript standard called nullish coalescing, which is a handy shorthand that will provide a default value if a variable is either null or undefined.

TypeScript 4.9.5
function nullishCheck(a: number | undefined | null) {
// Check if the passed variable 'a' is either undefined or null
// If it is, then print 'undefined or null'
// Else print the value of 'a'
console.log(`a : ${a ?? `undefined or null`}`);
}
// Call the function with a number
nullishCheck(1);
// Call the function with null
nullishCheck(null);
// Call the function with undefined
nullishCheck(undefined);
Prints value or undefined or null

Here, we have a single function named nullishCheck on lines 1–6 that accepts a single parameter named a that can be either a number, undefined, or null.

This function then logs the value of the variable a ...