Introduction
Ever tried to access deeply nested properties in a JavaScript object and ended up with an error saying null or undefined? Then probably you would have written some unpleasant-looking code to check whether that property exists or not. 😬
This JavaScript syntax will reduce the amount of code we will have to write and also clean up our code. 😀
What is "Optional Chaining"?
The optional chaining operator (?.) 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 or undefined), the expression returns a value of undefined.
What problem is it solving?
Lets's say I have an object e.g. user = {}
and through the course of using the app this gets populated. Let's say somewhere after a network call to get something like this:
let user = {
location : {
lat: 50,
long: 9
}
}
At another place I want to check if user.location.lat
exists.
if (user.location.lat) {
// do something
}
If it does not exists, this will cause an error. If user.location.lat
is undefined
, user.location
of course is undefined
as well.
"Cannot read property 'lat' of null" - Dev Tools error
That means I need to check it like this:
if (user.location) {
if (user.location.lat) {
// do something
}
}
or
if (user.location && user.location.lat) {
// do something
}
With the optional chaining operator(?.) you don't have to explicitly test and short-circuit based on the state of user && user.location
before trying to access user.location.lat
If user && user.location
are null or undefined, the expression automatically short-circuits, returning undefined.
const userLocation = user.location?.lat;
By using the ?. operator instead of just ., JavaScript knows to implicitly check to be sure user.location is not null or undefined before attempting to access user.location.lat
This looks much better to read and feels natural. It does exactly the same thing our first code block does while also improving the readability of our code and cleans it up. You can also use this operator to access functions and other properties. If you would like to learn more about this, please refer --> MDN Optional Chaining
Don’t overuse the optional chaining!
We should use?.
only where it’s ok that something doesn’t exist.
For example, if according to our coding logicuser
object must exist, butlocation
is optional, then we should writeuser.location?.street
, but notuser?.address?.street
Thanks for reading this article 💖
I hope that now you have a better understanding of the optional chaining operator and how to use it. If you have any questions please reach out to me at @prem_Kantikar 😋
âš¡ Happy Coding.