Skip to content

Nullish Coalescing

This lesson explains Nullish Coalescing with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.

ES6+ Nullish Coalescing Overview

The nullish coalescing operator ?? returns the right-hand value only when the left-hand value is null or undefined. It provides a safer default-value pattern than || in many real-world cases.

Nullish coalescing is commonly used for configuration defaults, API response fallbacks, form values, and optional chaining expressions where 0, "", or false are valid values.

Feature Description
Introduced In ES2020
Operator ??
Checks For null and undefined only
Ignores 0, "", false, NaN
Often Paired With ?. optional chaining
Common Uses Defaults, config, API data, function parameters

Basic Nullish Coalescing Example

const username = null;
const role = undefined;
const theme = "dark";

console.log(username ?? "Guest");
console.log(role ?? "viewer");
console.log(theme ?? "light");

The fallback value is used only when the left side is null or undefined. Existing valid values such as "dark" are kept.

How Nullish Coalescing Works

JavaScript evaluates the left operand first. If it is nullish, the right operand is returned. Otherwise, the left operand is returned.

Step Description Example
Evaluate Left Check the first value. value ?? "default"
Is Nullish? Is it null or undefined? null, undefined
Use Fallback Return right-hand value. "default"
Keep Original Return left-hand value if valid. 0, "", false
Combine Safely Pair with optional chaining. user?.name ?? "Guest"

Nullish Coalescing vs OR Operator

const count = 0;
const label = "";
const active = false;

console.log(count || 10);
console.log(count ?? 10);

console.log(label || "Untitled");
console.log(label ?? "Untitled");

console.log(active || true);
console.log(active ?? true);

The || operator treats all falsy values as missing, while ?? only falls back for null and undefined.

?? vs || Comparison Table

Left Value left || "fallback" left ?? "fallback"
null "fallback" "fallback"
undefined "fallback" "fallback"
0 "fallback" 0
"" "fallback" ""
false "fallback" false

Configuration Defaults

function createAppConfig(
  options = {}
) {
  return {
    theme:
      options.theme ?? "light",
    pageSize:
      options.pageSize ?? 20,
    showSidebar:
      options.showSidebar ?? true
  };
}

const config =
  createAppConfig({
    pageSize: 0,
    showSidebar: false
  });

console.log(config);

Nullish coalescing is ideal for config objects because 0 and false are often intentional user choices rather than missing values.

With Optional Chaining

const user = {
  profile: {
    name: "Alex"
  }
};

const name =
  user?.profile?.name ?? "Guest";

const city =
  user?.address?.city ?? "Unknown";

console.log(name);
console.log(city);

Optional chaining safely accesses nested values, and nullish coalescing provides a fallback when the result is null or undefined.

Function Parameter Defaults

function greet(
  name,
  punctuation
) {
  const safeName =
    name ?? "Guest";

  const safePunctuation =
    punctuation ?? "!";

  return `Hello ${safeName}${safePunctuation}`;
}

console.log(greet("Sam"));
console.log(greet("Sam", ""));
console.log(greet(null, "?"));

Use nullish coalescing when empty strings or other falsy but valid values should not be replaced automatically.

API Response Fallbacks

const response = {
  data: {
    user: {
      displayName: "",
      score: 0
    }
  }
};

const displayName =
  response?.data?.user?.displayName ??
  "Anonymous";

const score =
  response?.data?.user?.score ?? 0;

console.log(displayName);
console.log(score);

API data often includes empty strings or zero values that should be preserved. Nullish coalescing avoids overwriting them incorrectly.

Chaining Nullish Coalescing

const primary = null;
const secondary = undefined;
const tertiary = "Backup Value";

const result =
  primary ??
  secondary ??
  tertiary;

console.log(result);

You can chain multiple ?? operators to try several fallback values in order until a non-nullish value is found.

Common Nullish Coalescing Use Cases

  • Setting default configuration values.
  • Handling missing API response fields.
  • Providing fallback text for optional user data.
  • Working with form inputs that may be empty strings.
  • Combining with optional chaining for safe nested access.
  • Preserving valid zero and false values in app state.
  • Choosing backup values from multiple variables.

Nullish Coalescing Best Practices

  • Use ?? when only null or undefined should trigger a fallback.
  • Use || when any falsy value should trigger a fallback.
  • Pair ?? with ?. for safe nested defaults.
  • Prefer explicit defaults in function parameters when appropriate.
  • Do not mix ?? with && or || without parentheses.
  • Choose fallback values that match the expected data type.
  • Use chaining only when the fallback order is clear.

Common Nullish Coalescing Mistakes

  • Replacing || with ?? without understanding the difference.
  • Expecting ?? to fallback on empty strings or zero.
  • Mixing ?? with || without parentheses and getting syntax errors.
  • Using nullish coalescing when explicit validation is required.
  • Assuming fallback values are deeply merged into objects.
  • Creating overly long chained expressions that are hard to read.
  • Using ?? when the left side should never be nullish by design.

Key Takeaways

  • The ?? operator provides defaults for nullish values only.
  • It preserves valid values such as 0, "", and false.
  • It is safer than || for many default-value scenarios.
  • It works well with optional chaining for nested data access.
  • Choose between ?? and || based on whether falsy values are valid.

Pro Tip

If 0, false, or "" are valid values in your app, prefer ?? over || for default handling.