Difficulty: Beginner
Explain the optional chaining (?.) and nullish coalescing (??) operators. How do they differ from && and ||, and when should you use each?
Optional chaining (?.) safely accesses a property, calls a method or indexes into a value that might be null or undefined: if the left side is nullish, the whole expression short-circuits to undefined instead of throwing a TypeError. Nullish coalescing (??) returns the right-hand operand only when the left is null or undefined, unlike ||, which falls back on any falsy value such as 0, '' or false. Both arrived in ES2020 and are supported in every modern browser and Node.js 14+.
obj?.prop: property accessobj?.[expr]: computed access, for example orders?.[0]fn?.(args): call only if fn is not nullish, useful for optional callbacks like onSuccess?.(data)Short-circuiting covers the rest of the chain. In user?.address.city, if user is nullish the result is undefined and .city is never evaluated. But if user exists and address is undefined, .city still throws, so you need user?.address?.city when each level may be missing.
|| treats every falsy value as missing: false, 0, -0, 0n, '', NaN, null, undefined. That causes real bugs:
Value of a | `a \ | \ | 'default'` | a ?? 'default' |
|---|---|---|---|---|
0 | 'default' | 0 | ||
'' | 'default' | '' | ||
false | 'default' | false | ||
NaN | 'default' | NaN | ||
null or undefined | 'default' | 'default' |
If a cart's discount is legitimately 0 rupees, discount || 50 silently applies a fifty rupee default. discount ?? 50 keeps the 0. Use ?? for defaults whenever 0, '' or false are valid values; use || only when any falsy value really should be replaced.
Before ES2020 people wrote user && user.address && user.address.city. That works but returns the first falsy value it meets: if user.address is '', the result is '', not undefined. Optional chaining only checks for null and undefined, so ?. is both shorter and more precise.
?? cannot be mixed with && or || without parentheses: a || b ?? c is a SyntaxError. Write (a || b) ?? c.?. cannot be on the left of an assignment: user?.name = 'x' is a SyntaxError.new Foo?.() and optional chaining in tagged templates are not allowed.?. everywhere. If a value must exist (for example a required API field), let the code throw so the bug surfaces instead of hiding it as undefined.config.timeout ??= 5000 assigns only if the current value is nullish, and count ||= 1 assigns if it is falsy.?. checks only the value immediately to its left; obj.method?.() still throws if obj itself is undefined.const response = {
data: {
restaurant: { name: 'Meghana Foods', ratings: [4.5, 4.2] },
},
};
console.log(response.data?.restaurant?.name);
console.log(response.data?.offers?.[0]?.code); // offers missing
console.log(response.data?.restaurant?.ratings?.[1]);
const callbacks = { onSuccess: msg => `ok: ${msg}` };
console.log(callbacks.onSuccess?.('paid'));
console.log(callbacks.onError?.('failed')); // no onError, no crash
// Short-circuit: the function is never called when user is null
const user = null;
let calls = 0;
user?.profile[(calls++, 'name')];
console.log('calls:', calls);
Each ?. stops evaluation when the value to its left is nullish, including any expressions later in the chain. Optional calls are handy for callbacks that may not be provided.
function buildConfig(options) {
return {
retries: options.retries ?? 3,
retriesWrong: options.retries || 3,
label: options.label ?? 'Untitled',
verbose: options.verbose ?? true,
};
}
console.log(buildConfig({ retries: 0, label: '', verbose: false }));
const settings = { timeout: null, theme: 'dark' };
settings.timeout ??= 5000; // assigned: was null
settings.theme ??= 'light'; // skipped: already set
console.log(settings);
?? respects intentional zero, empty string and false values, while || overwrites them. The ??= operator assigns only when the current value is null or undefined.
Optional Chaining, Nullish Coalescing, Short-circuit Evaluation, Falsy Values, Logical Assignment