Optional chaining
Why optional chaining
Have you write the following code before?
1 | if (user && user.address && user.address.street) { |
With optional chaining operator, you don’t need so many &&
to get a deeply nested property.
1 | console.log(user?.address?.street); |
How to use optional chaining
The optional chaining (?.) operator accesses an object’s property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined
instead of throwing an error.
Access object’s property
1 | const person = { |
Call a function
1 | function doSomething(onContent, onError) { |
With optional chaining, you don’t need too check weather onError
is defined or not.
1 | function doSomething(onContent, onError) { |
Short circuit
When using optional chaining, if the left operand is null
or undefined
, the expression will not be evaluated, for instance:
1 | let i = 0; |
?. not work for non-declared root object
Optional chaining can not be used with a non-declared root object, but can be used with a root object that is null or undefined.
1 | console.log(a?.b); // Uncaught ReferenceError: a is not defined |
In javascript, not defined
and undefined
are two different concepts. See undefined vs not defined