Sub topic 12
When Not to Use These Operators
This chapter assumes you already know how ?., ?.[], ?.(), ?? and ??= behave, as covered in the earlier chapters. You should also be comfortable with throwing errors with throw and catching them with try...catch.
Optional chaining and nullish coalescing make missing values quiet. That is useful when a missing value is normal and expected. It hurts when a missing value means something has gone wrong, because the error that would have pointed you to the problem never happens. This chapter covers how to tell the two cases apart, the overuse patterns that show up in code review, and the cases where ?? is the wrong default operator.
The Core Question: Is Absence Expected?
Before you write ?. or ??, ask whether null or undefined is a valid state for this value in this place.
- Expected absence: an optional profile photo, a config key the user may leave out, an API field documented as nullable, a callback the caller may not pass. Handling these quietly is correct.
- Unexpected absence: a required function argument, a record you just inserted, a DOM element your own HTML always renders, a field your API contract guarantees. If one of these is missing, the program is in a broken state, and it should stop.
The operators can't tell these cases apart. They treat every nullish value as fine. You make that call when you decide where to put them.
Failure Mode 1: Hiding Bugs Behind Silent `undefined`
Here is a function that has been "made safe":
function formatOrder(order) {
return `Order ${order?.id} for ${order?.customer?.email}`;
}
console.log(formatOrder(undefined));
// "Order undefined for undefined"This doesn't crash. The string "Order undefined for undefined" can end up in an email, a database row, or a log line. Someone finds it days later, far from the code that caused it, with no stack trace pointing to the caller that passed undefined.
If an order without a customer is impossible, say so in the code:
function formatOrder(order) {
if (order == null || order.customer == null) {
throw new TypeError("formatOrder: expected an order with a customer");
}
return `Order ${order.id} for ${order.customer.email}`;
}
try {
formatOrder(undefined);
} catch (err) {
console.log(err.message); // "formatOrder: expected an order with a customer"
}
console.log(formatOrder({ id: 7, customer: { email: "[email protected]" } }));
// "Order 7 for [email protected]"The error now shows up right where the bad data came in, and the message explains what was expected. A plain TypeError: Cannot read properties of undefined would also have been better than the silent version. A crash is easier to debug than a wrong value.
Failure Mode 2: Chaining Every Link
Code like this is a warning sign:
const city = response?.data?.user?.address?.city;Every ?. says "this link may be nullish." That is rarely true of all of them. Suppose the API contract guarantees response.data.user, and only address is optional. Write that down precisely:
const response = { data: { user: { name: "Ada", address: null } } };
const city = response.data.user.address?.city;
console.log(city); // undefinedThe precise version has two benefits:
- It documents the data shape. A reader can see that
addressis the optional part. With?.on every link, the code tells the reader nothing about the shape. - It keeps the guaranteed links loud. If a server change drops
data, the precise version throws right away. The blanket version returnsundefinedand the bug moves somewhere else.
Here's a rule of thumb: put ?. directly after the value that can be nullish, and nowhere else.
Failure Mode 3: Optional Calls That Swallow Typos
?.() is meant for callbacks and methods that may not exist. It also hides misspellings:
const logger = { info: (msg) => console.log("INFO", msg) };
logger.inof?.("order saved"); // nothing happens, no error
logger.info("order saved"); // INFO order savedlogger.inof is undefined, so the optional call quietly does nothing, and nothing gets logged. If logger.info always exists, call it directly so a typo throws TypeError: logger.inof is not a function. Keep ?.() for hooks that really are optional, such as an onProgress option the caller may leave out.
Failure Mode 4: Defaults That Hide Configuration Errors
?? is good for optional settings. It is risky for required ones, because a missing value turns into a plausible-looking default:
const env = {}; // DATABASE_URL was forgotten in deployment
const dbUrl = env.DATABASE_URL ?? "postgres://localhost:5432/dev";
console.log(dbUrl); // "postgres://localhost:5432/dev"In production, this either fails to connect with a confusing network error or, worse, connects to the wrong database. A required setting should have no default:
function requireEnv(env, name) {
const value = env[name];
if (value == null || value === "") {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
const env = { DATABASE_URL: "postgres://db.internal:5432/app" };
console.log(requireEnv(env, "DATABASE_URL"));
// "postgres://db.internal:5432/app"
try {
requireEnv({}, "DATABASE_URL");
} catch (err) {
console.log(err.message); // "Missing required environment variable: DATABASE_URL"
}Use ?? only for values that have a sensible default in every environment, such as a log level or a page size.
Failure Mode 5: Expecting `??` to Validate
?? reacts only to null and undefined. Values that are present but invalid pass straight through:
const raw = "abc";
const port = Number(raw) ?? 3000;
console.log(port); // NaN (NaN is not nullish, so the default is ignored)
const name = " " ?? "Guest";
console.log(name); // " "NaN, empty strings, whitespace, negative numbers and wrong types all count as "present." If a value needs to be valid, check it explicitly:
function parsePort(raw, fallback = 3000) {
if (raw == null) return fallback; // missing: use the default
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new RangeError(`Invalid port: ${raw}`);
}
return port;
}
console.log(parsePort(undefined)); // 3000
console.log(parsePort("8080")); // 8080
try {
parsePort("abc");
} catch (err) {
console.log(err.message); // "Invalid port: abc"
}Here ??-style logic handles only the missing case. Validation handles everything else.
When `||` Is the Right Choice
Earlier chapters warned that || replaces valid values like 0. Sometimes, though, you want to replace every falsy value. The usual case is text input, where an empty string means "nothing entered":
function displayName(input) {
return input?.trim() || "Guest";
}
console.log(displayName(" Ada ")); // "Ada"
console.log(displayName("")); // "Guest"
console.log(displayName(" ")); // "Guest"
console.log(displayName(undefined)); // "Guest"With ??, displayName("") would return "" and show a blank name. The question to ask is whether 0, "" or false is a meaningful value for this field. If one is meaningful, use ??. If all of them mean "nothing," || states that intent directly.
Failure Mode 6: Guarding Values That Can Never Be Nullish
Some values can't be null or undefined at that point in the code. Putting ?. on them adds noise and misleads readers:
const items = [1, 2, 3];
console.log(items?.length); // 3, but items is a const array and can never be nullish
const result = [1, 2, 3].map((n) => n * 2);
console.log(result?.[0]); // 2, but map always returns an arrayEach extra ?. makes the reader stop and wonder when items could be missing. It can't be, so the reader's time is wasted. It also spreads: once a file is full of defensive chains, people copy the habit without thinking.
A Better Structure: Validate at the Boundary
Most overuse comes from not knowing what shape the data has. The fix is to check the data once, where it enters your program (an API response, a config file, user input), and then rely on the checked shape everywhere else.
function normalizeUser(raw) {
if (raw == null || typeof raw.id !== "number") {
throw new TypeError("normalizeUser: user id is required");
}
return {
id: raw.id,
name: raw.name?.trim() || "Anonymous", // optional, blank means missing
pageSize: raw.settings?.pageSize ?? 20, // optional, 0 is not valid but not expected
tags: raw.tags ?? [], // optional, empty array is a fine default
};
}
function renderUser(user) {
// No ?. needed: normalizeUser guarantees the shape
return `${user.id}: ${user.name} (${user.tags.length} tags, ${user.pageSize}/page)`;
}
const user = normalizeUser({ id: 1, name: " Ada ", settings: null });
console.log(renderUser(user)); // "1: Ada (0 tags, 20/page)"All the optional handling lives in one function. Downstream code like renderUser uses plain property access. If the shape ever breaks, it throws right away instead of returning undefined.
Quick Reference
| Situation | Use | Reason | Column | Column |
|---|---|---|---|---|
| Field documented as optional or nullable | `?.` on that field only | Absence is a normal state | ||
| Required argument or guaranteed field | Plain access, throw early | Absence is a bug that should be visible | ||
| Optional callback or hook | `?.()` | Caller may not pass it | ||
| Method that always exists | Plain call | `?.()` would swallow typos | ||
| Optional setting where `0` or `false` is valid | `??` | Keeps valid falsy values | ||
| Text input where `""` means "nothing" | `\ | \ | ` | All falsy values should fall back |
| Required config value | Explicit check, no default | A default hides deployment errors | ||
| Present but possibly invalid value | Explicit validation | `??` does not catch `NaN` or bad input | ||
| Value that can never be nullish | Plain access | `?.` only adds noise |
Exercises
Exercise
A teammate fixes a crash report "TypeError: Cannot read properties of undefined (reading 'total')" by changing invoice.summary.total to invoice?.summary?.total. The invoice comes from a function that should always return an invoice with a summary. What is wrong with this fix, and what should they do instead?
Show answer
The fix hides the symptom. A missing invoice or summary breaks the function's contract, so the real bug is wherever an invoice without a summary was produced. With the change, undefined spreads into totals, displays or calculations and shows up later, far from the cause. They should find out why summary was missing and fix that. If they want a guard, it should throw a clear error (for example if (invoice?.summary == null) throw new Error("invoice summary missing")) rather than return undefined.
Exercise
For each value, choose ??, ||, or explicit validation, and explain why: (a) a volume setting from 0 to 100 that the user may omit, (b) a search box value where an empty string means "show all", replaced with "*", (c) a maxRetries value parsed from a string environment variable.
Show answer
(a) ??, because 0 is a valid volume and must not be replaced. (b) ||, because an empty string should fall back to "", and ?? would keep "". You could write `query?.trim() || "". (c) Explicit validation. Number("abc") returns NaN, which is not nullish, so ?? would let it through. Use ?? or == null only to handle the missing case, then check Number.isInteger(value) && value >= 0` and throw if the check fails.
Exercise
Rewrite const zip = order?.shipping?.address?.zip ?? "N/A"; given this contract: order is always defined, order.shipping is always an object, and address is null for digital orders.
Show answer
const zip = order.shipping.address?.zip ?? "N/A"; Only address can legitimately be null, so it gets the only ?.. If order or shipping is ever missing, the code throws right away instead of quietly showing "N/A".