The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish ( null or undefined ), the expression short-circuits with a return value of undefined.
When used with function calls, it returns undefined, if the given function does not exist.
This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.
Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object.
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
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 accessed obj.first.second
directly without testing obj.first
.
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 obj.first.second
:
let nestedProp = obj.first?.second;
By using the ?. operator instead of just . , JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second. If obj.first is null or undefined, the expression automatically short-circuits, returning undefined instead of throwing an error.