Nullable nested data
Read optional fields from API responses or configuration objects without manually checking every intermediate object.
JS Puzzles · Const
Optional chaining (?.) safely accesses nested properties, computed properties, or methods when a value may be null or undefined. It short-circuits that chain and returns undefined instead of throwing.
Optional chaining safely accesses a property, computed property, or method when an earlier value may be null or undefined. It stops that continuous chain and returns undefined instead of throwing; a method call is skipped when the method is absent.
obj?.prop
obj?.[prop]
obj.method?.()undefined when the value before the optional chain is null or undefined; otherwise it produces the requested property value or call result.
?. links to traverse nested data whose intermediate objects may be missing.?. ends the chain and yields undefined instead of causing the usual property-access error.obj?.prop, obj?.[key], and obj.method?.().undeclared?.prop still raises a ReferenceError. Declare the variable first, even if its value is undefined.?. protects only the immediately preceding value. Add another optional chain for each nullable link, such as user?.address?.street.const user = { profile: { name: "Ada" } };
console.log(user.profile?.name); // "Ada"
console.log(user.settings?.theme); // undefined
console.log(user.profile?.["name"]); // "Ada"
console.log(user.notify?.("hello")); // undefinedEach optional chain continues only when the value before ?. is neither null nor undefined.
Read optional fields from API responses or configuration objects without manually checking every intermediate object.
Invoke an optional callback or object method only when it exists.
Read a property whose key is computed at runtime while safely handling a missing base object.
Optional chaining evaluates the left side and, if it is null or undefined, stops the chain and produces undefined. If the value exists, normal property access or invocation proceeds.
Follow-up: What happens with obj?.a.b when obj.a is undefined? The chain does not protect b; use obj?.a?.b when both links may be absent.
The documented forms are obj?.prop, obj?.[prop], and obj.method?.(). They respectively guard property access, computed-property access, and calling a method that may not exist.
Follow-up: How can you safely call a possibly absent function stored directly in fn? Use fn?.(); it returns undefined when fn is null or undefined.
Optional chaining short-circuits evaluation, so an expression used as a computed property is not evaluated when the left value is null or undefined. The short circuit applies only to one continuous chain.
Follow-up: Does grouping preserve the whole-chain short circuit? No: grouping ends the chain, so a later access can still throw if its grouped result is undefined.
nullish coalescing operator (??)property accessmethod callssquare brackets