Sub topic 7
Defaults with ?? and why it is not ||
This chapter assumes you know TypeScript union types, how strictNullChecks makes null and undefined part of a type, and how optional chaining (?.) works. It covers the nullish coalescing operator ??, how it differs from ||, and the mistakes that follow from mixing them up.
The problem: supplying a default
With strictNullChecks on, a value of type string | undefined cannot be used as a string until you handle the missing case. The usual fix is to supply a default. JavaScript has long offered || for this:
function greet(name: string | undefined): string {
const who = name || "stranger";
return "Hello, " + who;
}
console.log(greet("Ada"));
console.log(greet(undefined));This type-checks and works for ordinary names. The trouble is what || actually tests. It does not ask "is this value missing?" It asks "is this value falsy?" Falsy values in JavaScript are false, 0, -0, 0n, "", null, undefined, and NaN. Any of them on the left sends || to the right-hand side.
What ?? does
The nullish coalescing operator ?? returns its right-hand operand only when the left-hand operand is null or undefined. Every other value, including 0, "", false, and NaN, is kept.
const retries = 0;
const withOr = retries || 3; // 3, because 0 is falsy
const withNullish = retries ?? 3; // 0, because 0 is not null or undefined
console.log(withOr, withNullish);A retry count of 0 is a deliberate choice, such as "do not retry". || silently overrides it with 3. ?? respects it.
The following table shows which operator keeps each left-hand value.
| Left-hand value | `value \ | \ | "default"` | `value ?? "default"` |
|---|---|---|---|---|
| `"text"` | `"text"` | `"text"` | ||
| `""` | `"default"` | `""` | ||
| `0` | `"default"` | `0` | ||
| `false` | `"default"` | `false` | ||
| `NaN` | `"default"` | `NaN` | ||
| `null` | `"default"` | `"default"` | ||
| `undefined` | `"default"` | `"default"` |
How the compiler types the result
TypeScript removes null and undefined from the left operand's type and unions the rest with the right operand's type. For a ?? b, the result type is roughly NonNullable<typeof a> | typeof b.
function pageSize(requested: number | null | undefined): number {
const size = requested ?? 20; // number
return size;
}Here requested ?? 20 has type number, because null | undefined is stripped from the left side and the right side is number. This is why ?? is the standard way to turn a nullable type back into a non-nullable one.
Compare this with ||. For string | undefined, the result of || is also string, so the compiler does not warn about the difference. For a number | undefined left side, || loses the 0 case at runtime, and the types give you no hint. The compiler cannot tell you that || was the wrong choice.
The diagram below is in the required form.
Combining ?? with optional chaining
Optional chaining returns undefined when it stops early, so ?. and ?? are a natural pair. The chain short-circuits to undefined, and ?? replaces that with a fallback.
interface User {
name: string;
address?: { city?: string };
}
function cityOf(user: User): string {
return user.address?.city ?? "unknown";
}
console.log(cityOf({ name: "Ada" }));
console.log(cityOf({ name: "Ada", address: { city: "London" } }));
console.log(cityOf({ name: "Ada", address: { city: "" } }));The third call prints an empty string, because "" is a present value. With ||, it would print unknown. Whether that is what you want depends on your domain. If an empty city should count as missing, say so explicitly rather than relying on falsiness:
function cityOrUnknown(city: string | undefined): string {
return city === undefined || city === "" ? "unknown" : city;
}Being explicit documents the decision and survives later refactoring.
Choosing between ?? and ||
Use ?? when the question is "was a value provided?" Use || when the question is "is this value usable?" and every falsy value should be rejected.
- Numeric options such as counts, timeouts, ports, and offsets: use
??, because0is usually valid. - Boolean flags: use
??, becausefalseis a real choice.flag || truecan never producefalse. - Strings where empty means "not filled in", such as a display name from a form:
||can be appropriate, but an explicit check is clearer. - Boolean conditions, such as
isAdmin || isOwner: use||. This is its normal logical role.
interface Options {
timeoutMs?: number;
verbose?: boolean;
}
function resolve(options: Options) {
return {
timeoutMs: options.timeoutMs ?? 5000,
verbose: options.verbose ?? true,
};
}
console.log(resolve({ timeoutMs: 0, verbose: false }));This prints { timeoutMs: 0, verbose: false }. Replacing both ?? with || would print { timeoutMs: 5000, verbose: true }, which ignores the caller's explicit settings.
The assignment form: ??=
??= assigns only when the target is currently null or undefined. It is shorthand for a ?? (a = b).
interface Config {
retries?: number;
label?: string | null;
}
const config: Config = { label: null };
config.retries ??= 3;
config.label ??= "default";
console.log(config);Both properties start missing, so both are assigned. If config.retries were 0, it would stay 0. The right side is evaluated only when assignment happens, so an expensive default is not computed needlessly. The same applies to ?? itself: the right operand is skipped when the left is present.
Edge cases and gotchas
Mixing ?? with || or && needs parentheses
JavaScript forbids combining ?? directly with || or && without parentheses. This is a syntax error, not a type error.
const a: number | null = null;
const b = 0;
const c = 5;
// const bad = a ?? b || c; // SyntaxError
const good = (a ?? b) || c;
const alsoGood = a ?? (b || c);
console.log(good, alsoGood);The two forms give different results (5 and 5 here, but not in general), so the parentheses record your intent.
The right-hand side is not narrowed by the left
?? removes null and undefined from the result, but only for the expression itself. It does not narrow the original variable.
function length(s: string | null): number {
const t = s ?? "";
// s is still string | null here; t is string
return t.length;
}Use t, or narrow s with an if check, when you need the non-null value afterward.
A default can hide a bug
?? makes a missing value disappear. If the value should always exist, a silent default can mask a real problem, such as a failed lookup or a typo in a key name. For required data, throw instead:
function required<T>(value: T | null | undefined, message: string): T {
if (value === null || value === undefined) {
throw new Error(message);
}
return value;
}
const port = required(process.env.PORT, "PORT is not set");Reserve ?? for values that are legitimately optional.
Types that cannot be nullish
If the left operand's type cannot be null or undefined, the right side is unreachable. TypeScript reports an error in some cases, such as when the left side is a literal or an expression that is never nullish, and linters such as typescript-eslint's no-unnecessary-condition can flag the rest. Treat that warning as a sign that your types and your defensive code disagree.
Empty values from external data
Data from forms, query strings, and JSON often uses "" or "0" for "nothing entered". ?? will not replace these. Normalize at the boundary, converting empty strings to undefined once, and then use ?? inside your code.
function parsePort(raw: string | undefined): number {
const cleaned = raw === "" ? undefined : raw;
return cleaned === undefined ? 8080 : Number(cleaned);
}
console.log(parsePort(""), parsePort("3000"), parsePort(undefined));Common errors
| Mistake | Effect | Fix | Column | Column |
|---|---|---|---|---|
| `count \ | \ | 10` where `0` is valid | A real `0` becomes `10` | `count ?? 10` |
| `flag \ | \ | true` | The result is always `true` | `flag ?? true` |
| `a ?? b \ | \ | c` without parentheses | Syntax error | Add parentheses around one pair |
| `??` on a value that is never nullish | Dead code, possible lint warning | Remove it or fix the type | ||
| Using `??` for a required value | Missing data is hidden | Throw an error instead | ||
| Expecting `??` to treat `""` as missing | The empty string is kept | Check `=== ""` explicitly |
Summary of the model
??checks for exactlynullandundefined.||checks for any falsy value.- The result type of
a ?? bisNonNullable<A> | B. ?.producesundefinedon a missing link, and??supplies the fallback.??=assigns only when the target is nullish.- Mixing
??with||or&&requires parentheses. - A default is a decision. Use it for optional values, and throw for required ones.
Exercise
The function below should return the configured port, or 8080 when none is given. A caller passes 0 to ask the operating system to choose a free port, but the function returns 8080 instead. Fix it, and state the value returned for each input: 0, undefined, and null.
function getPort(port: number | null | undefined): number {
return port || 8080;
}
Show answer
Replace || with ??: return port ?? 8080;. The input 0 returns 0, because 0 is not null or undefined. The input undefined returns 8080. The input null returns 8080. The original || version returned 8080 for all three, because 0, undefined, and null are all falsy.
Exercise
Given const label: string | undefined = "", what do label ?? "none" and label || "none" evaluate to, and what is the type of each expression?
Show answer
label ?? "none" evaluates to "" because the empty string is neither null nor undefined. label || "none" evaluates to "none" because the empty string is falsy. Both expressions have type string, so the compiler gives no warning about the different runtime results.
Exercise
Why does const x = a ?? b || c; fail, and what are the two ways to fix it?
Show answer
JavaScript makes it a syntax error to combine ?? with || or && in one expression without parentheses, because the intended grouping would be ambiguous. Write (a ?? b) || c to apply the default first, or a ?? (b || c) to apply || to the right-hand side only.