Select Page

In TypeScript, double question marks (`??`) are used as the nullish coalescing operator. The nullish coalescing operator is used to provide a default value for a variable or expression when the value on the left-hand side is `null` or `undefined`, but it does not provide a default value for other falsy values like `0`, `false`, or an empty string `””`.

Here’s the basic syntax of the nullish coalescing operator:

const result = someValue ?? defaultValue;

.If someValue is not null or undefined, the result will be assigned the value of someValue. If someValue is null or undefined, the result will be assigned the value of defaultValue.

Here’s an example:

const username = null;

const defaultUsername = “Guest”;

const result = username ?? defaultUsername;

console.log(result); // Output: “Guest”

In this example, the username variable is null, so the nullish coalescing operator assigns the value of defaultUsername to the result variable.

It’s important to note that the nullish coalescing operator is specifically designed to handle cases where you want to provide a default value for null or undefined and not for other falsy values. If you want to provide a default value for any falsy value (including 0, false, or ""), you can use the logical OR operator ||.