In TypeScript, the double question mark (??) is known as the nullish coalescing operator. It is used to provide a default value for a variable that may be null or undefined.

Here is an example of how the nullish coalescing operator works:

let x: number | null | undefined = undefined;
let y = x ?? 10;
console.log(y); // Output: 10

In the example above, the variable x is defined as a number, or null, or undefined. It is assigned the value undefined. The nullish coalescing operator is then used to assign the value of x to y, with a default value of 10 if x is null or undefined. Since x is undefined, the value of y becomes 10.

The nullish coalescing operator is similar to the logical OR operator (||), but it only assigns a default value if the value on the left side is null or undefined. If the value on the left side is any other falsy value (such as 0 or an empty string), the nullish coalescing operator will not assign the default value.

let x: number | null | undefined = 0;
let y = x ?? 10;
console.log(y); // Output: 0

In the example above, the variable x is assigned the value 0, which is a falsy value. The nullish coalescing operator is used to assign the value of x to y, with a default value of 10 if x is null or undefined. Since x is not null or undefined, the value of y becomes 0.

The nullish coalescing operator can be a useful tool in TypeScript for providing default values for variables that may be null or undefined, without accidentally overwriting any other falsy values.

Leave a Reply

Your email address will not be published. Required fields are marked *