Nullish coalescing in Typescript

Nullish coalescing in TypeScript is a feature that allows you to provide a default value when dealing with null or undefined values. It is represented by the ?? operator. This operator is useful in scenarios where you want to ensure that a variable has a meaningful value, falling back to a default if the variable is null or undefined.

Syntax and Usage

The syntax for nullish coalescing is straightforward:


let value = someVariable ?? defaultValue;

Here, someVariable is checked, and if it is null or undefined, defaultValue is used. Otherwise, someVariable is used.

Example

Let’s look at a few examples to understand how nullish coalescing works:


let name: string | null = null;
let defaultName: string = "Default Name";

let result = name ?? defaultName;
console.log(result);  // Output: "Default Name"

in this example, name is null, so the defaultName is used.

Difference from the Logical OR (||) Operator

It’s important to understand the difference between the nullish coalescing operator (??) and the logical OR operator (||). The logical OR operator will return the right-hand side value if the left-hand side value is falsy (e.g., false, 0, NaN, "", null, undefined). In contrast, the nullish coalescing operator only considers null and undefined.


let value1 = 0;
let defaultValue1 = 10;

let result1 = value1 || defaultValue1;
console.log(result1);  // Output: 10, because 0 is falsy

let result2 = value1 ?? defaultValue1;
console.log(result2);  // Output: 0, because 0 is not null or undefined

Nested Nullish Coalescing

You can use nullish coalescing with nested expressions to handle multiple potential null or undefined values:


let firstName: string | null = null;
let middleName: string | null = null;
let lastName: string = "Taylor";

let fullName = firstName ?? middleName ?? lastName;
console.log(fullName);  // Output: "Taylor"

Combining with Optional Chaining

Nullish coalescing can be particularly powerful when combined with optional chaining (?.). Optional chaining allows you to safely access nested properties that might not exist, without throwing an error.


type User = {
  profile?: {
    name?: string;
  };
};

let user: User = {};

let userName = user.profile?.name ?? "Anonymous";
console.log(userName);  // Output: "Anonymous"

In this example, user.profile?.name safely attempts to access name, returning undefined if profile or name does not exist. The nullish coalescing operator then provides a fallback value of “Anonymous”.