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.

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.

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 or Core Idea

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

Minimal form

const result = value ?? "default";

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

How JavaScript decides

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.

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.

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.

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.

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

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.

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

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

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.

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

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

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.

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

Fix: Add parentheses so the grouping is explicit.

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.

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.

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.

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

Parentheses make the intent explicit and reduce mistakes during refactoring.

8. Limitations and Edge Cases

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.

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

11. Practice Exercise

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

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

Hint: Use ?? instead of ||.

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);

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 (?.).