Optional Chaining and Nullish Coalescing: Safe Access Without Boilerplate
Two operators that replaced half the defensive checks in my code. Here is how they differ and where they fall short. Optional chaining and nullish coalescing are the two operators that most reduced boilerplate in my JavaScript. Together they replace a large class of defensive checks that existed only to avoid throwing on null or undefined. They are small features, but using them correctly requires understanding exactly which values they treat as needing a default and which they preserve. Optional Chaining Short-Circuits Optional chaining, written as a question mark followed by a dot, evaluates the left side and, if it is null or undefined, short-circuits the entire expression to undefined. This means deeply nested property access that used to require a chain of truthiness checks becomes a single expression. The operator also works for method calls and bracket access, so you can optionally call a function only if it exists. const city = user?.address?.city; const handler = config?.onUpdate?.(); Important: optional chaining short-circuits on null and undefined only. If an intermediate value is zero, an empty string, or false, the chain continues normally. This is exactly the behavior you want for accessing…