Since apparently we must continue to reduce code readability to cater to lazy programmers who want to save a few keystrokes not “having to” check for existing parent properties on nested objects.
The optional chaining operator provides a way to simplify accessing values through connected objects when it’s possible that a reference or function may be undefined or null.
For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:
let nestedProp = obj.first && obj.first.second;
The value of
obj.first is confirmed to be non-null (and non-undefined) before then accessing the value of
obj.first.second. This prevents the error that would occur if you simply accessed
obj.first.second directly without testing
With the optional chaining operator (
?.), however, you don’t have to explicitly test and short-circuit based on the state of
obj.first before trying to access
let nestedProp = obj.first?.second;
By using the
?. operator instead of just
obj.first is not null or undefined before attempting to access
obj.first is null or undefined, the expression automatically short-circuits, returning undefined.