Optional Chaining
As JavaScript keep growing and changing every year, ES2020 came up with may helpful features that will makes your life easier while coding, today we will talk about Optional chaining.
Let’s see what is optional chaining and how it makes your code simpler when accessing potentially null
or undefined
properties.
What’s optional chaining
according to Mozilla developer , optional chaining is:
permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The
?.
operator functions similarly to the.
chaining operator, except that instead of causing an error if a reference is nullish (null
orundefined
), the expression short-circuits with a return value ofundefined
. When used with function calls, it returnsundefined
if the given function does not exist.
The problem
You maybe just start learning JavaScript or maybe you didn’t face bug with null object field in an object but it’s very common and happened a lot .
For example, some of our users have addresses, but few did not provide them. Then we can’t safely read user.address.street
:
It will trow an error cause address property not exist in our user object
To solve this problem before optional chaining came out, we used &&
operator or if statement
It will not trow an error or break your code but will console log undefined
.
Imagine if you have very deep object, and how long your if statement or &&
will be. with optional chaining will be more easier
It will console log undefined
no errors.