JavaScriptEasy
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 value | x || "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 size0, an empty display name the user chose, a disabled flagfalse, a price of0.||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 ifxis falsy.x ??= y: assign ifxis 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}56// Real bugs fixed by ??7const settings = { volume: 0, nickname: "", notifications: false };8console.log(settings.volume || 50, settings.volume ?? 50); // 50 09console.log(settings.notifications || true, settings.notifications ?? true); // true false1011// Where || is the right choice: replace empty strings too12const query = "";13console.log(`Results for: ${query || "everything"}`); // Results for: everything1415// Assignment operators16const opts = { retries: 0, label: "" };17opts.retries ??= 3; // kept: 0 is a real value18opts.label ||= "Untitled"; // replaced: empty string19console.log(opts); // { retries: 0, label: "Untitled" }2021// Mixing needs parentheses22const 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.