Sub topic 12
When Not to Use These Operators
This chapter assumes you already know how ?., ?? and ??= behave, including how chains short-circuit. The question here is a judgment call: when does reaching for them make your code worse?
The Core Rule: Absence Must Be Expected
Optional chaining and nullish coalescing say "this value may legitimately be missing, and that is fine." That is a claim about your data. If the claim is false, the operators don't remove the bug. They hide it.
Consider a function that formats an order. Every order in your system must have a customer.
function formatOrder(order) {
return `${order?.customer?.name ?? "Unknown"} owes $${order?.total ?? 0}`;
}
console.log(formatOrder({ customer: { name: "Ada" }, total: 42 }));
// "Ada owes $42"
console.log(formatOrder({ customr: { name: "Ada" }, totl: 42 }));
// "Unknown owes $0"The second call has typos in both property names. Without the operators, the code would throw a TypeError or print undefined right away, and you would see the bug. With them, it quietly prints wrong data. An invoice saying "$0" is worse than a crash, because nobody notices it.
Fail Fast When Data Is Required
If a value is required, check for it and throw a clear error. The failure then shows up where the problem starts, not three functions later.
function formatOrder(order) {
if (order == null) {
throw new Error("formatOrder: order is required");
}
if (order.customer == null) {
throw new Error(`formatOrder: order ${order.id} has no customer`);
}
// Discount really is optional, so ?? fits here.
const discount = order.discount ?? 0;
return `${order.customer.name} owes $${order.total - discount}`;
}
console.log(formatOrder({ id: 7, customer: { name: "Ada" }, total: 42 }));
// "Ada owes $42"Both kinds of code sit together here. The required fields get explicit checks, and the one optional field gets ??.
Common Overuse Patterns
| Pattern | Problem | Better approach |
|---|---|---|
| `a?.b?.c?.d` on every link by habit | Hides which link was missing and why | Put `?.` only after links that are documented as optional |
| `config.apiUrl ?? ""` | An empty URL fails later with a confusing network error | Throw at startup if required config is missing |
| `user?.id` right after `const user = getUser()` that never returns null | Signals possible absence that cannot happen, which misleads readers | Use plain `user.id` |
| `?? 0` on numbers used in math | Turns "unknown" into a real-looking value | Keep `undefined` and handle it in the display layer |
| `callback?.()` on a callback that callers must pass | A forgotten argument silently does nothing | Check `typeof callback !== "function"` and throw |
Where These Operators Shine
Avoiding overuse doesn't mean avoiding the operators. They fit well when:
- The data shape is optional by design, such as user preferences, optional API fields, or feature flags.
- You read values for display, where a placeholder is the right result.
- You call optional hooks or event handlers, like
options.onProgress?.(percent). - You fill in documented defaults with
??=when normalizing an options object.
Exercises
Exercise
A function receives settings from a trusted internal module that always supplies settings.theme. A teammate writes const theme = settings?.theme ?? "light";. What is the risk, and what would you write instead?
Show answer
If settings or settings.theme is missing, that is a bug in the internal module, and the code hides it by quietly switching to "light". Since the value is required, write const theme = settings.theme;, or add an explicit check that throws, so the bug surfaces where it happens.
Exercise
An API response may or may not include an optional avatarUrl field, and the UI shows a generic icon when it is absent. Is user.avatarUrl ?? DEFAULT_AVATAR appropriate? Why?
Show answer
Yes. The field is optional by design, its absence is expected, and the default (a generic icon) is a correct result for display, not a placeholder that hides an error.