How to Use the Double Question Mark (??) Operator in TypeScript?

As a developer working on a project for a client in New York, I encountered an issue where user input fields were often left blank. These null or undefined values caused unexpected behavior in the application. To handle this, I used the double question mark operator to provide default values seamlessly. In this tutorial, I will explain the double question mark (??) operator in TypeScript, also known as the nullish coalescing operator.

To use the double question mark (??) operator in TypeScript, which is known as the nullish coalescing operator, you can handle null or undefined values effectively by providing default values. This operator returns the right-hand operand when the left-hand operand is null or undefined, ensuring your code is cleaner and more readable. For example, let result = value ?? defaultValue; assigns defaultValue to result if value is nullish.

What is the Double Question Mark (??) Operator in TypeScript?

The double question mark (??) operator in TypeScript is a logical operator that returns the right-hand side operand when the left-hand side operand is null or undefined. If the left-hand side operand is neither null nor undefined, it returns the left-hand side operand. This operator was introduced in TypeScript 3.7 and is particularly useful for handling default values without resorting to more verbose conditional statements.

TypeScript Double Question Mark Syntax

The syntax for the double question mark operator is:

let result = value ?? defaultValue;

Here, result will be assigned the value of value if it is not null or undefined; otherwise, it will be assigned defaultValue.

Syntax

Why Use the Double Question Mark (??) Operator?

  1. Improved Code Readability: By clearly defining fallback values, the operator makes your code cleaner and easier to understand.
  2. Avoiding Unnecessary Null Checks: It reduces the need for verbose null checks, streamlining your code.
  3. Enhanced Error Handling: Ensures your application behaves predictably even when some values are missing or undefined.

Check out Exclamation Mark in TypeScript

TypeScript Double Question Mark Examples

Let me show you examples of using the double question mark in TypeScript.

Example 1: Set Default Values

Consider a scenario where you are developing an application for a client. You need to ensure that user preferences are set to default values if not provided.

interface UserPreferences {
    theme?: string;
    notifications?: boolean;
}

const defaultPreferences: UserPreferences = {
    theme: "light",
    notifications: true,
};

const userPreferences: UserPreferences = {
    theme: "dark",
};

const finalPreferences = {
    theme: userPreferences.theme ?? defaultPreferences.theme,
    notifications: userPreferences.notifications ?? defaultPreferences.notifications,
};

console.log(finalPreferences);
// Output: { theme: "dark", notifications: true }

In this example, the theme is set to “dark” as provided by the user, while notifications fall back to the default value true.

The exact output can be seen in the screenshot below. I executed the above TypeScript code using VS code.

typescript double question mark

Check out Difference Between == and === in TypeScript

Example 2: Handle API Responses

Let me show you another real example.

Suppose you’re working on a project for a tech startup in San Francisco that fetches user data from an API. Sometimes, the API response might not include all fields.

interface UserData {
    name?: string;
    age?: number;
    city?: string;
}

const apiResponse: UserData = {
    name: "John Doe",
    city: "Los Angeles",
};

const userName = apiResponse.name ?? "Anonymous";
const userAge = apiResponse.age ?? 30;
const userCity = apiResponse.city ?? "Unknown";

console.log(`Name: ${userName}, Age: ${userAge}, City: ${userCity}`);
// Output: Name: John Doe, Age: 30, City: Los Angeles

In this case, the name and city fields are provided by the API, while age defaults to 30.

Example 3: Combine with Logical OR

The double question mark operator can be combined with other logical operators like the logical AND (&&) and logical OR (||) to create more complex conditions.

Here is another example where I have explained how to use the double question mark operator with logical OR in Python.

const input = null;
const fallback = "Default Value";
const result = input ?? fallback || "Another Default";
console.log(result); // Output: "Default Value"

Here, input is null, so the double question mark operator assigns fallback, which is “Default Value”. The logical OR operator is not evaluated because the left-hand side is already a truthy value.

Here is the exact output in the screenshot below:

double question mark typescript

Conclusion

The double question mark (??) operator in TypeScript handles nullish values. In this tutorial, I explained how to use the double question mark (??) operator in TypeScript with a few real examples.