Sub topic 7
Defaults with `??` and why it is not `||`
This chapter assumes you know basic TypeScript types, union types, optional properties, and JavaScript truthiness. You should also have strictNullChecks enabled. The key idea is that ?? handles missing values, while || handles all falsy values.
What nullish coalescing does
The nullish coalescing operator, written ??, chooses its left side unless that value is null or undefined. If the left side is nullish, it evaluates and returns the right side.
function displayName(name: string | null | undefined): string {
return name ?? "Anonymous";
}
console.log(displayName("Ada")); // Ada
console.log(displayName(null)); // Anonymous
console.log(displayName(undefined)); // AnonymousThe expression name ?? "Anonymous" is useful when null and undefined mean “no value,” but other values remain valid.
?? short-circuits. This means JavaScript does not evaluate the right side when the left side is present.
function loadFallback(): string {
console.log("Fallback loaded");
return "default";
}
const first = "configured" ?? loadFallback();
// The fallback function is not called.
const second = null ?? loadFallback();
// Logs "Fallback loaded".Why `??` differs from `||`
The logical OR operator, ||, uses truthiness. It returns the right side for every falsy left-side value, including:
false0NaN""nullundefined
That behavior is sometimes correct, but it can replace meaningful data.
const retries = 0;
const label = "";
const retriesWithOr = retries || 3; // 3
const retriesWithNullish = retries ?? 3; // 0
const labelWithOr = label || "untitled"; // "untitled"
const labelWithNullish = label ?? "untitled"; // ""The retry count 0 may mean “do not retry,” and an empty label may be intentional. ?? preserves both values.
| Expression | Uses fallback for `0`? | Uses fallback for `""`? | Uses fallback for `null`? | Column | Column |
|---|---|---|---|---|---|
| `value | fallback` | Yes | Yes | Yes | |
| `value ?? fallback` | No | No | Yes |
Choose || when every falsy value should trigger the fallback. Choose ?? when only an absent value should trigger it.
Combining `?.` and `??`
Optional chaining, ?., produces undefined when it reaches a missing property, so it works naturally with ??.
interface Settings {
language?: string;
notifications?: {
email?: boolean;
};
}
function notificationStatus(settings: Settings): string {
const enabled = settings.notifications?.email ?? true;
return enabled ? "enabled" : "disabled";
}
console.log(notificationStatus({})); // enabled
console.log(notificationStatus({
notifications: { email: false }
})); // disabledThe value false is preserved because ?? only checks for null and undefined. Writing settings.notifications?.email || true would incorrectly turn an explicit false into true.
The evaluation can be pictured as a sequence:
Other defaulting rules
A parameter default applies when the argument is undefined, but not when it is null.
function greeting(name = "Guest"): string {
return `Hello, ${name}`;
}
console.log(greeting()); // Hello, Guest
console.log(greeting(undefined)); // Hello, Guest
// greeting(null); // Error if strictNullChecks is enabledIf a parameter explicitly allows null, handle it with ??:
function greetingOrEmpty(name: string | null | undefined): string {
return `Hello, ${name ?? "Guest"}`;
}Exercise
What do these expressions produce: 0 || 10, 0 ?? 10, false || true, and false ?? true?
Show answer
They produce 10, 0, true, and false, respectively. || replaces falsy values, while ?? replaces only null and undefined.