TypeScript
Nullish Coalescing
Use a default value only for null/undefined.
By EZ4Code Team
nullish-coalescingnullish
Code
// ?? only triggers on null/undefined
const x = null ?? "default"; // "default"
const y = undefined ?? "default"; // "default"
const z = 0 ?? "default"; // 0 (not the default)
const w = "" ?? "default"; // ""
// Difference from ||
const a = 0 || "default"; // "default" (0 is falsy)
const b = 0 ?? "default"; // 0
// Practical usage
function getConfig(options?: Partial<Config>) {
const timeout = options?.timeout ?? 3000;
return { timeout };
}Explanation
?? targets only null/undefined, while || applies to all falsy values.