JS Nullish Coalescing Operator (??) Full Guide

Learn the JavaScript nullish coalescing operator (??) to provide default values only for null and undefined, avoiding common pitfalls of the || operator.

JavaScriptbeginner
9 min read

Setting default values in JavaScript has always been tricky. The logical OR operator (||) was the traditional tool for this, but it treats 0, "", and false as reasons to use the fallback. That causes real bugs when those are valid values. The nullish coalescing operator (??) fixes this by only falling back when the left side is null or undefined.

This guide covers the ?? operator in depth: how it works, why it replaced || for defaults, and the practical patterns that make your code more robust.

The Problem with || for Default Values

The || operator returns the right side whenever the left side is falsy. JavaScript has six falsy values: false, 0, "", null, undefined, and NaN. That makes || too aggressive for default values:

javascriptjavascript
function createPlayer(name, score, active) {
  return {
    name: name || "Anonymous",
    score: score || 100,
    active: active || true
  };
}
 
// Looks correct, but has bugs
const player = createPlayer("", 0, false);
console.log(player);
// { name: "Anonymous", score: 100, active: true }
// BUG: empty string, 0, and false were all valid inputs!

The intent was to default only when values are actually missing (not provided). But || treats 0 as missing, "" as missing, and false as missing. These are legitimate values that got silently replaced.

How ?? Works

The nullish coalescing operator (??) returns the right side only when the left side is null or undefined. All other values, including 0, "", false, and NaN, pass through:

javascriptjavascript
function createPlayer(name, score, active) {
  return {
    name: name ?? "Anonymous",
    score: score ?? 100,
    active: active ?? true
  };
}
 
const player = createPlayer("", 0, false);
console.log(player);
// { name: "", score: 0, active: false }
// Correct! All valid inputs preserved

Here is the complete truth table:

Left Side Valuevalue || fallbackvalue ?? fallback
nullfallbackfallback
undefinedfallbackfallback
0fallback0
"" (empty string)fallback""
falsefallbackfalse
NaNfallbackNaN
"hello""hello""hello"
424242

Practical Use Cases

Configuration Objects with Valid Falsy Values

javascriptjavascript
function applyConfig(userConfig) {
  const config = {
    volume: userConfig.volume ?? 75,
    brightness: userConfig.brightness ?? 100,
    muted: userConfig.muted ?? false,
    username: userConfig.username ?? "Guest",
    retryCount: userConfig.retryCount ?? 3
  };
  return config;
}
 
// User explicitly wants volume at 0 and muted true
const result = applyConfig({ volume: 0, muted: true, username: "" });
console.log(result);
// { volume: 0, brightness: 100, muted: true, username: "", retryCount: 3 }
// All user values preserved, only missing ones get defaults

Function Parameter Defaults

While default parameters handle undefined, they do not trigger on null. The ?? operator handles both:

javascriptjavascript
// Default params only trigger on undefined, NOT null
function greet(name = "World") {
  console.log(`Hello, ${name}!`);
}
greet(null); // "Hello, null!" - default not triggered
 
// ?? handles both null and undefined
function greetBetter(name) {
  const safeName = name ?? "World";
  console.log(`Hello, ${safeName}!`);
}
greetBetter(null);      // "Hello, World!"
greetBetter(undefined); // "Hello, World!"
greetBetter("");        // "Hello, !"  - empty string preserved

Chaining Multiple Fallbacks

You can chain ?? to try multiple sources before settling on a final default:

javascriptjavascript
const userTheme = null;
const savedTheme = undefined;
const systemTheme = "dark";
const defaultTheme = "light";
 
const theme = userTheme ?? savedTheme ?? systemTheme ?? defaultTheme;
console.log(theme); // "dark" (first non-nullish value)

This reads like a priority list: try user preference first, then saved preference, then system setting, and finally the hardcoded default.

Combining ?? with Optional Chaining

The ?? operator pairs perfectly with optional chaining (?.) to safely access nested data and provide defaults in one expression:

javascriptjavascript
const response = {
  data: {
    user: {
      preferences: {
        theme: "dark"
      }
    }
  }
};
 
// Safe access + default in one line
const theme = response?.data?.user?.preferences?.theme ?? "light";
const lang = response?.data?.user?.preferences?.language ?? "en";
const fontSize = response?.data?.user?.preferences?.fontSize ?? 16;
 
console.log(theme);    // "dark"
console.log(lang);     // "en"
console.log(fontSize); // 16

This combination has become the standard pattern for handling API responses in modern JavaScript.

?? Cannot Mix with && or || Without Parentheses

JavaScript throws a syntax error if you mix ?? with && or || without explicit parentheses. This is a deliberate design decision to prevent ambiguous expressions:

javascriptjavascript
// SyntaxError - cannot mix without parentheses
// const result = a || b ?? c;
// const result = a && b ?? c;
 
// Correct - use parentheses to clarify intent
const result1 = (a || b) ?? c;  // Apply || first, then ??
const result2 = a || (b ?? c);  // Apply ?? first, then ||
const result3 = (a && b) ?? c;  // Apply && first, then ??

This rule exists because || and ?? have different semantics for falsy versus nullish values, and mixing them without parentheses would be confusing and error-prone.

Nullish Coalescing Assignment (??=)

The ??= operator assigns a value only if the current value is null or undefined. It is shorthand for if (x == null) x = value:

javascriptjavascript
const options = {
  color: null,
  size: 0,
  label: ""
};
 
options.color ??= "blue";    // null -> assigned "blue"
options.size ??= 10;         // 0 -> NOT assigned (0 is not nullish)
options.label ??= "Default"; // "" -> NOT assigned ("" is not nullish)
options.icon ??= "star";     // undefined -> assigned "star"
 
console.log(options);
// { color: "blue", size: 0, label: "", icon: "star" }

Compare with the OR assignment (||=):

OperatorAssigns When Left IsLeaves Alone
??=null or undefined0, "", false, NaN
||=Any falsy valueTruthy values only
&&=Any truthy valueFalsy values

Real-World Example: Form Data Processor

Here is a practical example processing form submissions where empty strings and zeros are valid inputs:

javascriptjavascript
function processFormData(formData) {
  // Parse raw form values with safe defaults
  const processed = {
    firstName: formData.get("firstName") ?? "",
    lastName: formData.get("lastName") ?? "",
    age: parseInt(formData.get("age")) || null,
    score: (() => {
      const raw = formData.get("score");
      const parsed = raw !== null ? Number(raw) : null;
      return Number.isNaN(parsed) ? null : parsed ?? 0;
    })(),
    newsletter: formData.get("newsletter") ?? "off",
    bio: formData.get("bio") ?? null
  };
 
  // Validate required fields
  const errors = [];
  if ((processed.firstName ?? "") === "") {
    errors.push("First name is required");
  }
  if ((processed.lastName ?? "") === "") {
    errors.push("Last name is required");
  }
 
  return { data: processed, errors, isValid: errors.length === 0 };
}

This pattern ensures that empty string inputs from forms are preserved as empty strings rather than being replaced with defaults. The ?? operator correctly distinguishes between "the user typed nothing" (empty string, a valid value) and "the field was not present" (null).

Common Mistakes to Avoid

Using || When ?? Is Needed

javascriptjavascript
// Bug: discount of 0% gets replaced with 10%
const discount = userDiscount || 10;
 
// Fix: only default when truly missing
const discount = userDiscount ?? 10;

Assuming ?? Works Like a Ternary

javascriptjavascript
const value = 0;
 
// ?? only checks null/undefined
const a = value ?? "fallback"; // 0 (not nullish)
 
// If you need to check for falsy, use || or a ternary
const b = value || "fallback";          // "fallback"
const c = value ? value : "fallback";   // "fallback"

Forgetting to Use Parentheses with Mixed Operators

javascriptjavascript
// Always wrap when mixing
const result = (config.debug || false) ?? defaultDebug;
// NOT: config.debug || false ?? defaultDebug (SyntaxError)

|| vs ?? Decision Guide

SituationUseWhy
Numeric values (0 is valid)??0 is not nullish
Boolean values (false is valid)??false is not nullish
String values (empty is valid)??"" is not nullish
Need to treat all falsy as "missing"|||| catches all falsy
API response data with unknown shape??Only null/undefined are truly missing
Feature flags (on/off)??false means "explicitly off"

Best Practices

  1. Default to ?? over || for all new code that sets fallback values. It produces fewer bugs because it respects 0, "", and false as valid data.
  2. Combine with ?. for safe nested access: obj?.nested?.value ?? default is the gold standard for defensive data access.
  3. Use ??= for lazy initialization of optional properties that should only be set once if missing.
  4. Always add parentheses when mixing ?? with || or && to make the evaluation order explicit.
  5. Document your choice when using || instead of ??. If you intentionally want falsy-fallback behavior, a comment explaining why prevents future developers from "fixing" it to ??.
Rune AI

Rune AI

Key Insights

  • Use ?? instead of || for defaults: it preserves 0, "", false, and NaN as valid values instead of replacing them
  • Pair with ?. for the safest data access: obj?.prop ?? fallback is the modern standard for defensive coding
  • ??= enables lazy initialization: assign default values only to properties that are actually null or undefined
  • Parentheses are mandatory with mixed operators: JavaScript throws a SyntaxError when ?? is combined with || or && without grouping
  • Choose || deliberately, not by habit: when you need falsy-fallback behavior, document why to prevent accidental migration to ??
RunePowered by Rune AI

Frequently Asked Questions

Can I use ?? with optional function parameters?

Yes. Use `??` in the function body when you need to default both `null` and `undefined` values. [Default parameters](/tutorials/programming-languages/javascript/how-to-use-default-parameters-in-js-functions) only trigger on `undefined`, so `??` is more comprehensive: `function save(data) { const name = data ?? "untitled"; }` handles `null`, which default params would not.

Does ?? short-circuit like || does?

Yes. If the left side is not `null` or `undefined`, the right side is never evaluated. This means `value ?? expensiveFunction()` will not call the function when `value` already has a non-nullish value. This makes `??` safe to use with expensive computations or side effects on the right side.

What is the operator precedence of ???

The `??` operator has lower precedence than most operators but higher precedence than the [ternary operator](/tutorials/programming-languages/javascript/javascript-ternary-operator-complete-syntax-guide) and assignment operators. It cannot be mixed with `||` or `&&` without parentheses. In practice, always use parentheses when combining `??` with other logical operators to make your intent clear.

Is ?? supported in TypeScript?

Yes, TypeScript has supported `??` since version 3.7 (released November 2019). TypeScript also provides strict null checking (`strictNullChecks`), which works harmoniously with `??` by ensuring you handle `null` and `undefined` explicitly throughout your codebase.

When should I still use || instead of ???

Use `||` when you intentionally want to fall through on any [falsy value](/tutorials/programming-languages/javascript/what-are-truthy-and-falsy-values-in-javascript), not just `null`/`undefined`. Common cases include: string inputs where empty strings should be treated as "not provided," or situations where `0` genuinely means "no value." Always add a comment explaining why you chose `||` over `??`.

Conclusion

The nullish coalescing operator (??) is the correct tool for setting default values in JavaScript. Unlike the || operator, it only triggers on null and undefined, preserving valid values like 0, empty strings, and false. Combined with optional chaining (?.) and the assignment variant (??=), it forms a complete toolkit for safe, predictable data handling.