Optional Chaining in JavaScript is used to return undefined
for accessing an object property that doesn't exist and whose parent property is nullish (null or undefined).
If you are unaware that property exists or not and you want to avoid the error that's being thrown, you may want to use optional chaining to get around with it.
In this article, you’ll learn how and when to use Optional Chaining. You’ll also learn when not to use Optional Chaining in JavaScript.
How it Works
First, let's explore what can go wrong when accessing a property in a nested object.
let person = {
name: "Murtuza",
work: () => {
return "Software Developer"
},
socials: {
github: {
username: "murtuzaalisurti",
link: "https://github.com/murtuzaalisurti",
proUser: {
is: 'no'
}
},
linkedin: {
username: "murtuzaali-surti",
link: "https://linkedin.com/in/murtuzaali-surti"
},
twitter: {
username: "murtuza_surti",
link: "https://twitter.com/murtuza_surti"
}
}
}
In the above object, let's try to access the property link
nested within the property website
. Can we?
console.log(person.website.link); //an error will be thrown
We get an error,
Cannot read property 'link' of undefined
The property website doesn't exist in the object!
But, let's add the property website
to the root object and set the value of it as null
.
website: null
Let's check if this works,
console.log(person.website.link); //an error will be thrown
We get a similar error,
Cannot read property 'link' of null
As mentioned in the above definition, we can use optional chaining to handle these types of errors! Here's how we can do that.
Syntax
// website: property to validate
// link: property to access
website?.link
The operator ?.
will check if the property on its left-hand side is null
or undefined
and if that's the case, then it will simply return undefined
without throwing any errors. In other words, this is also known as short-circuiting. Otherwise, it will return the value of the property on its right-hand side.
Not just that, you can also invoke a function if it exists using optional chaining.
person.work?.(args)
Also, you can access properties using []
brackets.
person.socials.github?.["username"]
What You Can’t Do
- You cannot apply optional chaining to the objects that are not declared yet. For example:
object?.prop // object is not defined
We haven't declared object
, thus it will throw an error.
- You cannot assign a value to this expression. In other words, the optional chaining expression can't be on the left-hand side.
The below code is not valid.
person.socials.github?.["username"] = "name" // not valid
When to Use Optional Chaining?
It's important to note that optional chaining should not be used when it's not necessary to do so. Only use optional chaining when you know that the property that you want to access is optional and not mandatory.
For example, in our object person
, we can keep the social media platforms optional, so we are not sure if a user has a social media account or not on a particular platform. For that, we can use optional chaining to check if a user has a social media account on a particular platform and if it exists, get the username.
person.socials.github?.["username"]
But, if we place the optional chaining operator at the root object, then it doesn't make any sense because the root object i.e. person
must exist and if it doesn't exist, we should get an error!
Conclusion
In this article, you learned what Optional Chaining in JavaScript is, how it works when to use it, and when not to use it.
To learn more about how Optional Chaining works, make sure to check out the MDN documentation on it for more details.
This post was originally published in Syntackle in collaboration with blog.shahednasser.com