The nullish coalescing operator ?? lets you provide a default value only when a variable is null or undefined. Unlike the logical OR operator (||), it does not treat other falsy values such as 0, false, or '' as “empty”.
This is especially useful when you want to keep valid falsy values and avoid accidentally overwriting them with a default.
?? checks only for null and undefined (called “nullish” values).0, false, and '' are kept as they are and do not trigger the default.?.) to safely access nested properties.Basic syntax of the nullish coalescing operator:
let result = value ?? defaultValue;
// If value is null or undefined → result = defaultValue
// Otherwise → result = value
Think of ?? as “use the left side if it is defined, otherwise fall back to the right side”.
Use ?? to provide safe defaults without losing valid falsy values:
let name;
let displayName = name ?? 'Guest';
console.log(displayName); // 'Guest'
let count = 0;
let total = count ?? 10;
console.log(total); // 0 (not 10, because 0 is not null or undefined)
The logical OR operator (||) treats many values as falsy (0, '', false, null, undefined, etc.). The nullish coalescing operator (??) only treats null and undefined as needing a default.
let value = '';
console.log(value || 'Default'); // 'Default' because '' is falsy
console.log(value ?? 'Default'); // '' because '' is not nullish
Use ?? when you want to preserve valid falsy values and only replace null or undefined.
Combine optional chaining (?.) and nullish coalescing for safer defaulting when dealing with nested objects or API responses.
const user = {
profile: {
name: 'Alex'
}
};
const username = user.profile?.name ?? 'Anonymous';
console.log(username); // 'Alex'
const settings = {};
const theme = settings.preferences?.theme ?? 'light';
console.log(theme); // 'light' because preferences is undefined
From the basic usage example:
name is undefined, so name ?? 'Guest' → 'Guest'.count is 0. Since 0 is not null or undefined, count ?? 10 → 0.From the comparison with OR:
value || 'Default' returns 'Default' because '' is falsy.value ?? 'Default' returns '' because the value is defined (not nullish).This shows why ?? is safer when empty strings, zero, or false are meaningful values in your logic.
null or undefined.?? instead of || when 0, false, or '' are valid values.value ?? default for user inputs or API fields where “empty” still has meaning.?. and ?? to safely access deep properties and provide clean defaults.?? with logical operators (&&, ||) to keep the intent clear.null and use ?? to print a default name.?? with values like 0, '', and false. Observe which ones are replaced.obj?.nested?.value ?? 'No value' to safely display a result.|| for defaults and replace it with ??. Check how the behavior changes.