Nullable nested data
Read deeply nested configuration or API data whose intermediate objects may be absent.
JS Puzzles · Const
Optional chaining safely accesses nested properties and optionally calls methods when an intermediate value may be null or undefined. A nullish value before ?. short-circuits the remaining chain and returns undefined.
Optional chaining places ?. at a property access, computed access, or function call that may be absent. If the value on its left is null or undefined, evaluation stops and the complete expression produces undefined; otherwise, the access or call proceeds normally.
obj?.prop
obj?.[prop]
obj.method?.()The accessed value or function result when the chain succeeds; otherwise undefined when an optional link encounters null or undefined.
const user = {
profile: {
getName() {
return "Ada";
}
}
};
const name = user?.profile?.getName?.();
const missing = user.settings?.theme;
console.log(name); // Ada
console.log(missing); // undefinedEach optional link checks the value immediately before it and stops the remaining chain when that value is nullish.
Read deeply nested configuration or API data whose intermediate objects may be absent.
Invoke an optional callback or method without first writing an explicit existence check.
Access a dynamically named property when the container itself may be missing.
It checks the value immediately to the left of ?. and stops if that value is null or undefined. The expression then evaluates to undefined instead of throwing for that optional step.
Follow-up: What happens with user?.profile.name? Only user is optional; if user exists but profile is nullish, .name is still unsafe.
The property form is obj?.prop, the computed form is obj?.[prop], and the optional-call form is obj.method?.(). The call form invokes the method only when that property exists.
Follow-up: Why use method?.() rather than obj?.method()? The former checks whether the method is callable at that property; the latter first checks obj and then performs a normal property access.
Optional chaining short-circuits later work in the same chain when the left side is undefined or null. Function calls or other operations to its right are not performed after that short circuit.
Follow-up: What should be verified in code review? Ensure each potentially absent intermediate value has an optional marker and that silently returning undefined is acceptable.
optional chainingnullish coalescing operatorproperty accessorsshort-circuit evaluation