JavaScriptEasy
What is nullish coalescing?
The nullish coalescing operator (??) returns its right-hand value only when the left-hand value is null or undefined; unlike ||, it keeps other falsy values such as 0, "" and false.
Why it exists
For years, defaults were written with ||: const port = config.port || 3000. That silently replaces valid values like 0, an empty string or false. ?? treats only "nothing" (null/undefined) as missing.
Nullish assignment
x ??= value sets x only if it is null or undefined. Handy for lazy initialisation: cache[key] ??= compute(key).
Rules and gotchas
- It short-circuits: the right side is evaluated only when needed.
- Cannot be mixed with
&&or||without parentheses:a || b ?? cis a syntax error; write(a || b) ?? c. - Works great after optional chaining:
obj?.deep?.value ?? fallback.
Choosing between || and ??
- Use
??for missing data: config options, API fields, function arguments. - Use
||when any falsy value should be replaced, e.g. turning an empty search string into a placeholder.
Default parameters vs ??
Default parameters only replace undefined, not null. If a caller might pass null, use ?? inside the function.
Code example
js
1const config = { port: 0, host: "", debug: false, timeout: null };23console.log(config.port || 3000); // 3000 <- wrong, 0 was intentional4console.log(config.port ?? 3000); // 056console.log(config.host ?? "localhost"); // ""7console.log(config.debug ?? true); // false8console.log(config.timeout ?? 5000); // 5000 (null -> default)9console.log(config.retries ?? 3); // 3 (undefined -> default)1011// Nullish assignment for lazy initialisation12const cache = {};13function getUser(id) {14 cache[id] ??= { id, loadedAt: "now" }; // created once15 return cache[id];16}17console.log(getUser(1) === getUser(1)); // true1819// Default params vs ??20function greet(name = "friend") {21 return `Hi ${name}`;22}23const greetSafe = (name) => `Hi ${name ?? "friend"}`;24console.log(greet(null), "|", greetSafe(null)); // Hi null | Hi friend2526// Mixing with || needs parentheses27const result = (config.host || null) ?? "fallback";28console.log(result); // fallback
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.