JavaScript Nullish Coalescing
The nullish coalescing operator (??) provides a fallback value when an expression is null or undefined.
If the left side is null or undefined, JavaScript returns the value on the right.
JavaScript
Using a fallback value.
const username = null;
const name = username ?? "Guest";
console.log(name);
The operator handles both null and undefined values.
JavaScript
Handling null and undefined.
const first = null ?? "Default";
const second = undefined ?? "Default";
console.log(first);
console.log(second);
Unlike the OR operator, ?? does not replace valid falsy values such as 0, false, or an empty string.
JavaScript
Preserving valid falsy values.
const count = 0;
const title = "";
console.log(count ?? 10);
console.log(title ?? "Untitled");
The || operator treats all falsy values as missing, while ?? only checks for null and undefined.
JavaScript
Comparing ?? with ||.
const count = 0;
console.log(count || 10);
console.log(count ?? 10);
Optional chaining and nullish coalescing work well together when reading optional nested data.
JavaScript
Safely reading nested data with a fallback.
const user = {};
const city = user.address?.city ?? "Unknown";
console.log(city);
It is useful when processing configuration or API data where a property may be missing.
JavaScript
Using a default configuration value.
const config = {
port: undefined,
debug: false
};
const port = config.port ?? 3000;
const debug = config.debug ?? true;
console.log(port);
console.log(debug);
Use ?? when you want a fallback only for null or undefined values while preserving values such as 0, false, and empty strings.