TypeScript ?? Operator

Do you want to know about the ?? operator in TypeScript?

I will explain here how to work with the nullish coalescing operator in TypeScript.

You will learn everything about the TypeScript ?? operator here. Mainly, I’ll show you exactly how it works, when to use it (and when not to), and share real-world examples that I use in my own projects.

What is TypeScript ?? Operator?

The ?? operator in TypeScript is called the nullish coalescing operator. It helps you handle cases where a value might be null or undefined—two of the most common sources of bugs in JavaScript and TypeScript.

Here’s the basic syntax:

const result = value ?? defaultValue;

This means:

  • If value is not null or undefinedresult will be value.
  • If value is null or undefinedresult will be defaultValue.

Why Not Just Use || (Logical OR)?

Great question! The logical OR operator (||) in TypeScript is often used for default values, but it treats any falsy value (like 0, '', or false) as needing a default. The ?? operator is smarter: it only checks for null or undefined, so you don’t accidentally override valid values like 0 or an empty string.

Let me show you different methods to use the ?? Operator in TypeScript.

Check out TypeScript Non-null Assertion Operator

Method 1: Using ?? for Default Values

Let me show you how I use the ?? operator in TypeScript with real examples.

Example 1: Handling API Data

Suppose you’re building a dashboard for a US-based business and pulling sales data from an API. Sometimes, the API might not return a value for monthlyRevenue:

interface SalesData {
  monthlyRevenue?: number | null;
}

const apiResponse: SalesData = { monthlyRevenue: null };

const revenue = apiResponse.monthlyRevenue ?? 0;
console.log(`This month's revenue: $${revenue}`); // Output: This month's revenue: $0

Here, if monthlyRevenue is either null or undefined, we default to $0. But if the API returns 0 (maybe no sales this month), we’ll still display $0—no accidental fallback!

Here is the exact output in the screenshot below:

nullish coalescing operator in TypeScript

Example 2: User Preferences

Let me show you another example.

Suppose an e-commerce site where users can select how many products to show per page. If the user hasn’t set a preference, you want to default to 20:

type UserSettings = {
  itemsPerPage?: number | null;
};

const userSettings: UserSettings = {};

const itemsToShow = userSettings.itemsPerPage ?? 20;
console.log(`Showing ${itemsToShow} products per page`);

Check out Import JSON Files in TypeScript

Method 2: Chaining ?? for Multiple Fallbacks

Sometimes, you might have more than one possible value to check. You can chain ?? operators to provide multiple fallbacks in TypeScript. Here is an example:

const envSetting = process.env.PAGE_SIZE ? Number(process.env.PAGE_SIZE) : undefined;
const configSetting = undefined;
const userSetting = null;

const pageSize = userSetting ?? configSetting ?? envSetting ?? 10;
console.log(`Page size: ${pageSize}`); // Uses the first non-nullish value

In this example, pageSize will be the first value that isn’t null or undefined. This is especially useful when merging settings from different sources (user, config file, environment variable, etc.).

You can see the exact output in the screenshot below:

TypeScript nullish coalescing operator

Read Push Objects into an Array in TypeScript

Method 3: Comparing ?? with || (Logical OR)

Let’s see why ?? is often better than || for default values.

const inputValue = 0;

const usingOr = inputValue || 100;      // 100
const usingNullish = inputValue ?? 100; // 0

console.log(`OR: ${usingOr}, Nullish: ${usingNullish}`);

With ||, 0 is treated as falsy, so you get 100—probably not what you want! With ??, only null or undefined trigger the default, so 0 is preserved.

Method 4: Nullish Coalescing in Function Parameters

You can use ?? inside functions to handle optional parameters elegantly.

function getTaxRate(state?: string | null): number {
  // Set default tax rate for the US if state is missing
  return state ?? 'CA' === 'CA' ? 0.0725 : 0.05;
}

console.log(getTaxRate('NY')); // 0.05
console.log(getTaxRate(null)); // 0.0725

Or, more commonly:

function getPageTitle(title?: string | null) {
  return title ?? 'Welcome to Our US Store!';
}

Check out Convert String To Double In TypeScript

Method 5: Using ?? in JSX/React (TypeScript)

If you’re building React apps with TypeScript, you’ll often use ?? when rendering components:

type User = { name?: string | null };

function Greeting({ user }: { user: User }) {
  return <h1>Hello, {user.name ?? 'Guest'}!</h1>;
}

If user.name is missing or null, the greeting will show “Guest”.

Best Practices for Using the ?? Operator in TypeScript

  • Use ?? for nullish checks: Only use it when you specifically want to check for null or undefined.
  • Don’t overuse: For simple cases, default parameters or destructuring with defaults can be more readable.
  • Avoid mixing with || in complex expressions: Mixing both can make your logic hard to follow. Stick to one style per line.
  • Be aware of older browser support: The ?? operator is not supported in Internet Explorer, but it’s safe for most modern US-based projects.

The TypeScript ?? operator is used to handle missing values in real applications.

If you haven’t used the ?? operator in TypeScript before, give it a try in your next project. If you have any questions or want to share your own tips, feel free to leave a comment below—I’m always happy to help fellow TypeScript developers.

You may also like the following tutorials:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App