Provide fallback values for null or undefined using the nullish coalescing operator.
Explanation
value ?? fallback: Returns the right-hand side operand when the left side isnullorundefined.- Unlike
||, it only checks for nullish values, not falsy values like0,'', orfalse. - Perfect for setting default values when you want to preserve falsy values that aren’t nullish.
Usage
To provide fallback values for nullish data, use the nullish coalescing operator:
const config = {
timeout: 0,
retries: null,
debug: false
};
// Using nullish coalescing
const timeout = config.timeout ?? 5000; // 0 (preserves falsy value)
const retries = config.retries ?? 3; // 3 (null becomes fallback)
const debug = config.debug ?? true; // false (preserves falsy value)
console.log({ timeout, retries, debug });
// Expected output: { timeout: 0, retries: 3, debug: false }
// Compare with logical OR
const timeoutOR = config.timeout || 5000; // 5000 (falsy 0 becomes fallback)
const retriesOR = config.retries || 3; // 3 (null becomes fallback)