JavaScript Nullish Coalescing

A Default — Only When Missing

JavaScript Nullish Coalescing

The `??` operator provides a default — but only when the value is `null` or `undefined`. It's the precise version of `||`.

4 min read Level 2/5 #nullish#coalescing#defaults
What you'll learn
  • Use `??` to provide defaults
  • Know the difference between `??` and `||`
  • Use `??=` to assign-if-missing

The nullish coalescing operator ?? returns its right-hand side when its left-hand side is null or undefined — otherwise it returns the left.

?? in action script.js
console.log(null ?? "fallback");       // "fallback"
console.log(undefined ?? "fallback");  // "fallback"

console.log(0 ?? "fallback");          // 0    ← 0 is NOT nullish
console.log("" ?? "fallback");         // ""   ← "" is NOT nullish
console.log(false ?? "fallback");      // false ← false is NOT nullish
▶ Preview: console

?? vs ||

This is the whole point of ??: || falls back on ANY falsy value (0, "", false). ?? only falls back on null/undefined.

?? vs || script.js
function getCount(input) {
  // Bug! 0 is a valid count, but || replaces it with 10.
  const usingOr = input || 10;

  // Correct: only fall back on null/undefined.
  const usingNullish = input ?? 10;

  console.log(`|| → ${usingOr}, ?? → ${usingNullish}`);
}

getCount(0);          // "|| → 10, ?? → 0"
getCount(undefined);  // "|| → 10, ?? → 10"
getCount(5);          // "|| → 5, ?? → 5"
▶ Preview: console

A Real Example

Reading config with a default script.js
function load(config) {
  const pageSize = config.pageSize ?? 20;
  const sortBy = config.sortBy ?? "createdAt";
  console.log({ pageSize, sortBy });
}

load({});                       // { pageSize: 20, sortBy: 'createdAt' }
load({ pageSize: 0 });          // { pageSize: 0,  sortBy: 'createdAt' }  ← 0 respected
load({ pageSize: 50, sortBy: "name" }); // { pageSize: 50, sortBy: 'name' }
▶ Preview: console

??= — Assign If Missing

A short way to write “if this isn’t set, set it to a default” is the nullish assignment operator ??=.

??= shortcut script.js
const settings = { theme: "dark" };

settings.theme ??= "light";   // theme exists → no change
settings.fontSize ??= 16;     // fontSize was undefined → set to 16

console.log(settings);  // { theme: 'dark', fontSize: 16 }
▶ Preview: console

Mixing With && / ||

?? cannot be used directly with && or || without parentheses — the language refuses, to prevent ambiguity.

Parens are required script.js
const a = null;
const b = false;

// console.log(a || b ?? "fallback"); // SyntaxError
console.log((a || b) ?? "fallback");  // false
console.log(a || (b ?? "fallback"));  // false
▶ Preview: console

Up Next

?? defaults a missing value. Its companion ?. safely accesses properties that might not exist.

JavaScript Optional Chaining →