Careeroza
Nullish Coalescing
The ?? Operator
a ?? b returns b only when a is null or undefined. Unlike ||, it keeps valid "falsy" values such as 0, "" and false.
Example
type Settings = { pageSize?: number; showOutOfStock?: boolean; searchPrefix?: string };
const saved: Settings = { pageSize: 0, showOutOfStock: false, searchPrefix: "" };
console.log("with ||:", saved.pageSize || 20, saved.showOutOfStock || true, JSON.stringify(saved.searchPrefix || "all"));
console.log("with ??:", saved.pageSize ?? 20, saved.showOutOfStock ?? true, JSON.stringify(saved.searchPrefix ?? "all"));
let cache: Map<string, number> | undefined;
cache ??= new Map(); // assign only if null/undefined
cache.set("hits", 1);
console.log(cache.get("hits"), cache.get("miss") ?? 0);Output
with ||: 20 true "all" with ??: 0 false "" 1 0
Combining ?. and ??
Tip: user?.address?.city ?? "Unknown" is the standard way to read deep, optional data with a fallback.