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"
}
}
}
console.log(person.website.link); //an error will be thrown
Cannot read property 'link' of undefined
website: null
console.log(person.website.link); //an error will be thrown
Cannot read property 'link' of null

Syntax

// website: property to validate
// link: property to access
website?.link
person.work?.(args)
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
  • 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.

person.socials.github?.["username"]

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Murtuza

Murtuza

Full Stack Developer | Content Creator | Technical Writer