JavaScript Nullish Coalescing (??): Fallback Values for null and undefined

The nullish coalescing operator gives you a clean way to choose a fallback value only when a value is actually missing. It is especially useful when you want to preserve valid falsy values such as 0, false, or an empty string.

Quick answer: Use ?? when you want the right-hand value only if the left-hand value is null or undefined. Unlike ||, it does not treat other falsy values as missing.

Difficulty: Beginner

You'll understand this better if you know: basic JavaScript values, how null and undefined work, and the idea of fallback values.

Browser support: Widely available since Mar 2023

1. What Is Nullish Coalescing?

The nullish coalescing operator (??) returns the value on its left unless that value is null or undefined. If the left side is nullish, JavaScript evaluates and returns the right side instead.

  • It is a binary operator, so it works with two expressions.
  • It is designed for missing values, not for all falsy values.
  • It helps you write safer default logic for user input, API data, and optional settings.

This operator is often compared with ||, but the difference is important: || falls back for any falsy value, while ?? falls back only for null or undefined.

2. Why Nullish Coalescing Matters

Many JavaScript values are valid even though they are falsy. For example, a quantity of 0, a boolean false, or an intentionally empty string can all be meaningful data. If you use the wrong fallback operator, you can accidentally replace valid input with a default value.

Nullish coalescing matters because it lets you distinguish between “missing” and “present but falsy.” That makes code easier to read and reduces bugs in forms, configuration objects, and API responses.

3. Basic Syntax

The syntax is simple: put the value you want to check on the left, and the fallback on the right.

Minimal form

JavaScript
const result = value ?? "default";

If value is null or undefined, result becomes "default". Otherwise, result keeps the original value.

How JavaScript decides

  • Left side is null → use the right side.
  • Left side is undefined → use the right side.
  • Left side is any other value → keep the left side.

This is a short-circuiting operator, so the right side is only evaluated when needed.

4. Step-by-Step Examples

Example 1: Defaulting a missing variable

If a value may not be provided, ?? is a compact way to choose a safe default.

JavaScript
let theme = null;
const activeTheme = theme ?? "light";

Because theme is null, activeTheme becomes "light".

Example 2: Preserving zero

When zero is a valid value, ?? avoids overwriting it with a fallback.

JavaScript
const quantity = 0;
const displayQuantity = quantity ?? 10;

The result stays 0, which is usually what you want for counts, indexes, and measurements.

Example 3: Reading optional object properties

API responses often omit fields. Nullish coalescing lets you handle that safely.

JavaScript
const user = { name: "Mina", nickname: undefined };
const nickname = user.nickname ?? "Guest";

Since nickname is undefined, the fallback is used.

Example 4: Combining with function return values

You can use ?? after a function call when the function may return a missing value.

JavaScript
function findTitle(items) {
  return items.find(item => item.featured)?.title ?? "Untitled";
}

If no featured item exists, the optional chain yields undefined, and the fallback title is returned.

5. Practical Use Cases

  • Using default values for form fields when the user leaves them unset.
  • Reading optional JSON fields from an API response.
  • Choosing configuration defaults without overriding valid falsy values.
  • Displaying a placeholder label when a property is missing.
  • Handling function parameters that may be omitted.

6. Common Mistakes

Mistake 1: Using || when zero is valid

New JavaScript developers often use || for defaults, then discover that valid values like 0 are replaced unexpectedly.

Problem: The expression treats 0 as missing because || checks any falsy value, not just null or undefined.

JavaScript
const timeout = 0;
const safeTimeout = timeout || 5000;

Fix: Use ?? so only nullish values trigger the fallback.

JavaScript
const timeout = 0;
const safeTimeout = timeout ?? 5000;

The corrected version keeps the intentional zero value.

Mistake 2: Expecting ?? to replace empty strings

An empty string is not nullish, so ?? will keep it. That is correct behavior, but it surprises people who want text-based fallback logic.

Problem: The left side is an empty string, so the fallback never runs even though the value looks blank.

JavaScript
const nickname = "";
const label = nickname ?? "Anonymous";

Fix: If you truly want to replace empty strings too, use a more explicit condition.

JavaScript
const nickname = "";
const label = nickname !== "" ? nickname : "Anonymous";

The fixed version matches the intent by checking for an empty string explicitly.

Mistake 3: Mixing ?? with || or && without parentheses

JavaScript does not allow arbitrary mixing of these operators without grouping, because the parser would otherwise create ambiguous logic. This often appears as a syntax error when you try to write a compact expression.

Problem: The expression combines nullish coalescing with logical operators in a way that JavaScript does not parse as written.

JavaScript
const value = null ?? false || "fallback";

Fix: Add parentheses so the grouping is explicit.

JavaScript
const value = (null ?? false) || "fallback";

The corrected version tells JavaScript exactly which operation to evaluate first.

7. Best Practices

Use ?? for missing data, not general truthiness

If the value can legitimately be 0, false, or "", prefer ??. This keeps meaningful values intact.

JavaScript
const pageSize = options.pageSize ?? 20;

This is clearer than assuming any falsy value means “not provided.”

Make fallback values obvious

Choose defaults that communicate intent, especially in shared code. A clear fallback helps other developers understand whether the value is required or optional.

JavaScript
const language = settings.language ?? "en";

That makes the default easy to spot and easy to change later.

Group mixed expressions with parentheses

If you combine ?? with other logical operators, use parentheses to show the evaluation order. That avoids syntax issues and makes the code easier to read.

JavaScript
const enabled = (config.flag ?? true) && isReady;

Parentheses make the intent explicit and reduce mistakes during refactoring.

8. Limitations and Edge Cases

  • ?? only checks for null and undefined; it does not treat empty strings, 0, or false as missing.
  • The right-hand expression is evaluated only when needed, which is useful for expensive defaults.
  • When reading nested properties, optional chaining often pairs naturally with ?? to avoid property access errors.
  • Operator precedence can be confusing in long expressions, so parentheses are often worth the extra characters.
  • Browser and runtime support is broad in modern environments, but older JavaScript engines may not support the operator without transpilation.

A common “not working” report is “why doesn’t ?? replace an empty string?” The answer is that an empty string is a real value, not a nullish one.

9. Practical Mini Project

In this small example, we build a settings display function that uses safe defaults for missing fields without overwriting valid falsy values.

JavaScript
const profile = {
  name: "Ava",
  age: 0,
  email: undefined,
  subscribed: false
};

function formatProfile(user) {
  const name = user.name ?? "Unknown";
  const age = user.age ?? "N/A";
  const email = user.email ?? "No email";
  const subscribed = user.subscribed ?? "Unknown";

  return `Name: ${name}, Age: ${age}, Email: ${email}, Subscribed: ${subscribed}`;
}

const summary = formatProfile(profile);

This example shows why ?? is more precise than ||: the age stays 0, and the subscribed state stays false instead of being replaced.

10. Key Points

  • ?? returns the left value unless it is null or undefined.
  • It is better than || when valid falsy values must be preserved.
  • Use it for defaults in data handling, configuration, and optional fields.
  • Parentheses help when combining it with other logical operators.
  • It pairs well with optional chaining for safe property access.

11. Practice Exercise

Rewrite the following logic so that it preserves valid falsy values but still supplies defaults for missing data.

  • Create a variable for title that defaults to "Untitled" only when the value is nullish.
  • Create a variable for views that defaults to 0 only when the value is nullish.
  • Create a variable for isPublic that defaults to true only when the value is nullish.

Expected output: Valid 0 and false values should remain unchanged.

Hint: Use ?? instead of ||.

Show solution
JavaScript
const data = {
  title: "",
  views: 0,
  isPublic: false
};

const title = data.title ?? "Untitled";
const views = data.views ?? 0;
const isPublic = data.isPublic ?? true;

console.log(title);
console.log(views);
console.log(isPublic);
Output✓ Tested · Node 24
0
false

Browser Support

FeatureChromeEdgeFirefoxSafariSafari iOS
Nullish coalescing
Widely available since Mar 2023
85+85+79+14+14+

Minimum versions with full support. Data from web-features 3.43.0 (the data behind MDN's Baseline), updated at every site build.

12. Final Summary

JavaScript nullish coalescing (??) is a focused operator for choosing fallback values when data is truly missing. It is one of the safest ways to provide defaults because it distinguishes null and undefined from other falsy values.

Once you start using ?? in forms, configuration objects, and API handling, your code becomes more predictable and less likely to overwrite meaningful values. If you often pair it with nested property access, the next operator worth learning is optional chaining (?.).