The error “Cannot read properties of undefined” has been in my life for too long. Optional chaining is the short fix, and it has worked in all browsers since July 2020.
There are three forms:
obj?.prop
obj?.[expr]
func?.(args)
If the part before ?. is null or undefined, the whole expression gives undefined and nothing to the right is evaluated. No exception.
const customerCity = customer.details?.address?.city;
onError?.(err.message);
The second line calls onError only if it exists. It pairs well with ?? for a default:
const city = customer?.city ?? "Unknown city";
Short-circuiting covers one continuous chain. Wrap part of it in parentheses and it stops working: (a?.b).c still throws a TypeError when a is null.
Caveats from MDN. You cannot assign to an optional chain: object?.property = 1 is a SyntaxError. ?.() only guards against a missing method. If the property exists but is not a function, it still throws, and when the object itself can be missing you need obj?.method?.(). The root variable must be declared, because ?. won’t save you from a ReferenceError. And be careful that it hides typos: a misspelled property name returns undefined quietly.
Further reading: MDN: Optional chaining