Optional chaining is the JavaScript operator ?. that accesses a property, calls a method or reads an array element only when the value on its left is not null or undefined, and otherwise short-circuits to undefined instead of throwing a TypeError. In browser JavaScript it is the standard way to read deeply nested data from API responses, DOM queries and configuration objects whose shape is not guaranteed.
The operator was standardized in ECMAScript 2020 and is supported by all current evergreen browsers. It replaces long guard expressions such as a && a.b && a.b.c with the shorter and more precise a?.b?.c, reducing boilerplate while making the intent, tolerance of a missing value, explicit.
How optional chaining evaluates an expression
Optional chaining evaluates the expression on the left of ?. first and checks whether the result is nullish, meaning exactly null or undefined. If it is nullish, evaluation of the entire remaining chain stops and the expression returns undefined. If it is any other value, including 0, an empty string or false, access continues normally.
This short-circuiting covers the whole chain, not just the next step. In user?.profile.address.city, a missing user ends evaluation immediately, so the later plain dots are never reached. However, if user exists but profile is undefined, the next plain dot still throws, because only the position marked with ?. is guarded.
The operator comes in three syntactic forms, each guarding a different kind of access.
| Form | Example | What it guards |
|---|---|---|
| Property access | obj?.prop | Reading a named property |
| Computed access | obj?.[key] | Bracket access, including array indexes |
| Optional call | fn?.(args) | Calling a function that may not exist |
Side effects inside a short-circuited chain are skipped. In obj?.[computeKey()], the function computeKey is never called when obj is nullish, which matters when the skipped expression would perform logging, counting or network work.
Rules and edge cases of the operator
Optional chaining has a small set of grammatical restrictions that frequently surprise developers. The most important is that an optional chain cannot be the target of an assignment: obj?.prop = 1 is a syntax error, because assigning to a value that might not exist has no sensible meaning.
| Expression | Result | Explanation |
|---|---|---|
| `null?.x` | undefined | Left side is nullish, chain stops |
| `0?.toFixed(1)` | “0.0” | Zero is not nullish, access proceeds |
| `obj.method?.()` | undefined if method missing | Guards the call, not the object |
| `obj?.prop = 1` | SyntaxError | Assignment target not allowed |
| `delete obj?.prop` | true when obj is nullish | Deletion is permitted and short-circuits |
| `new Foo?.()` | SyntaxError | Not allowed with constructors |
Optional call has a further nuance: obj.method?.() returns undefined only when method is nullish. If method exists but is not a function, such as a string, the call still throws a TypeError. Optional chaining tests for presence, not for type.
Parentheses also change the scope of short-circuiting. In (a?.b).c, the parentheses end the chain, so a nullish a produces undefined and the following .c then throws. Avoiding such wrappers keeps the protection intact.
Optional chaining compared with related patterns
Optional chaining is best understood alongside the older patterns it replaces and the operators it is usually combined with. The decisive difference from logical AND guards is that ?. checks only for null and undefined, whereas && stops on every falsy value.
| Pattern | Stops on | Typical role |
|---|---|---|
| Optional chaining `?.` | null and undefined | Safe access into uncertain structures |
| Logical AND guard `&&` | Any falsy value | Legacy guard, may skip valid 0 or empty string |
| Nullish coalescing `??` | Provides fallback for nullish | Supplying a default after a chain |
| Destructuring defaults | undefined only | Defaults when unpacking known shapes |
| try…catch | Any thrown error | Broad error handling, heavier and less precise |
The most common pairing is with nullish coalescing, as in settings?.theme ?? "light", which reads a value safely and supplies a default in one expression. Both operators share the same nullish semantics, so they compose without the falsy-value pitfalls of ||. Destructuring assignment offers a related but separate mechanism, because its defaults apply to undefined and not to null.
Practical use in browser code
In browser JavaScript, optional chaining is most valuable where data shape is decided outside the code: JSON from the Fetch API, results of DOM queries and optional browser features. A call such as document.querySelector("#menu")?.classList.add("open") does nothing when the element is absent instead of crashing the script.
- Parsing API responses whose optional fields may be omitted by the server.
- Feature detection, for example
navigator.share?.(data)on browsers that lack the Web Share API. - Calling optional callbacks passed to components, such as
options.onClose?.(). - Reading event details where some properties exist only for certain event types.
For legacy browsers, build tools such as Babel and TypeScript transpile the operator into equivalent conditional checks, so the syntax can be used even when older engines must be supported. Engines in current browsers handle ?. natively with negligible runtime cost, since the check is a single comparison against null and undefined.
Overuse and debugging pitfalls
The main risk of optional chaining is that it can hide genuine bugs. When a value is supposed to exist, writing ?. converts an informative TypeError into a silent undefined that surfaces later, far from its cause. Experienced developers therefore guard only values that are legitimately optional.
| Symptom | Likely cause | Correction |
|---|---|---|
| Silent blank UI | Required data guarded with ?. | Validate data and fail loudly |
| Chains of `?.` on every step | Unclear data contract | Define and check the expected shape once |
| TypeError despite `?.` | Unguarded later step or non-function call | Guard the correct position |
| Unexpected undefined in math | Missing fallback | Add ?? with a sensible default |
A practical rule is to treat each ?. as a statement about the data contract: this value may legitimately be absent. Validating external data at its boundary, for example right after parsing a response, keeps the rest of the code simpler and makes missing data visible.
Understanding it simply
Optional chaining is a short way of telling JavaScript to look for something only if the container exists. Imagine asking a colleague to fetch a file from a drawer in a cabinet. Without the check, the request fails loudly if there is no cabinet. With optional chaining, the answer is simply that nothing was found.
The symbol ?. does this check at each step where it is written. It prevents crashes from missing data, but it should be used only where something is truly allowed to be missing, so that real mistakes are still noticed.
Applied in practice
A frontend developer builds an order-tracking page that loads data from a shipping API with the Fetch API. Some orders include a delivery.courier.phone field, while orders not yet dispatched have no courier object at all. The original code used order.delivery.courier.phone and crashed the whole page for undispatched orders.
The developer rewrites the line as order.delivery?.courier?.phone ?? "Not yet assigned", while deliberately keeping order.id unguarded because every valid order must have one. After deployment, undispatched orders display a clear placeholder, the error reports in monitoring drop to zero for this view, and a malformed order without an ID still triggers a visible error that the team can investigate.