Nullish (??) vs OR (||)?

|| returns the right side when the left side is any falsy value (false, 0, "", NaN, null, undefined), while ?? returns it only when the left side is null or undefined; use ?? for "missing" and || for "empty or falsy".

Left valuex || "default"x ?? "default"
null / undefined"default""default"
0"default"0
"""default"""
false"default"false
NaN"default"NaN
"Ada""Ada""Ada"

When to use which

  • ?? for configuration and data where falsy values are valid: page size 0, an empty display name the user chose, a disabled flag false, a price of 0.
  • || when any falsy value should be replaced: show a placeholder when a search box is empty (query || "Search..."), fall back from an empty string to a default label.

Assignment versions

  • x ||= y: assign if x is falsy.
  • x ??= y: assign if x is null or undefined (lazy initialisation).

Syntax rule

?? cannot be mixed with || or && without parentheses: a ?? b || c is a syntax error. Write (a ?? b) || c.

Common bug

const volume = settings.volume || 50; turns a deliberate 0 into 50. Replacing || with ?? fixes it.

Code example

js
1const values = [null, undefined, 0, "", false, NaN, "Ada"];
2for (const v of values) {
3 console.log(String(v).padEnd(9), "||:", String(v || "default").padEnd(8), "??:", v ?? "default");
4}
5
6// Real bugs fixed by ??
7const settings = { volume: 0, nickname: "", notifications: false };
8console.log(settings.volume || 50, settings.volume ?? 50); // 50 0
9console.log(settings.notifications || true, settings.notifications ?? true); // true false
10
11// Where || is the right choice: replace empty strings too
12const query = "";
13console.log(`Results for: ${query || "everything"}`); // Results for: everything
14
15// Assignment operators
16const opts = { retries: 0, label: "" };
17opts.retries ??= 3; // kept: 0 is a real value
18opts.label ||= "Untitled"; // replaced: empty string
19console.log(opts); // { retries: 0, label: "Untitled" }
20
21// Mixing needs parentheses
22const fallback = (settings.nickname ?? null) || "Anonymous";
23console.log(fallback); // Anonymous

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app