JS Nullish Coalescing
In this page:
Basic Nullish Coalescing
The ?? operator returns its right-hand value only when the left side is exactly null or undefined, leaving other falsy values like 0 or an empty string untouched. It was added specifically to fix a common bug with ||-based defaults.
Example: Basic Nullish Coalescing
const value = null ?? "default";
console.log(value);
Nullish vs OR
Unlike ||, which falls back on ANY falsy value, ?? only falls back on null/undefined. This matters when 0, NaN, or '' are legitimate values you don't want silently replaced by a default.
Example: Nullish vs OR
console.log(0 || "fallback"); // "fallback" - || treats 0 as falsy
console.log(0 ?? "fallback"); // 0 - ?? only checks null/undefined
False and Empty Strings
false, 0, and '' are falsy but not nullish, so ?? treats them as valid values and does not fall back. This is exactly the case where || used to misbehave and ?? was introduced to fix.
Example: False and Empty Strings
console.log(false ?? "x"); // false
console.log(0 ?? "x"); // 0
console.log("" ?? "x"); // ""
With Objects
?? works the same way when the left side is a property read off an object, making it a natural fit for reading optional config fields without accidentally overriding intentional falsy values.
Example: With Objects
const config = { timeout: 0 };
console.log(config.timeout ?? 5000); // 0, a real intentional value
With Optional Chaining
?? and ?. (optional chaining) are commonly combined: chain safely into a possibly-missing object, then supply a default only if the final result is null or undefined.
Example: With Optional Chaining
const user = { address: null };
console.log(user?.address?.city ?? "Unknown");
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: