How optional chaining in JavaScript helps reducing code complexity

Let's take an example of an author object with nested structure,

const author = {
  firstName: 'Param',
  lastName: 'Harrison',
  social: {
    url: 'https://jsmates.com',
    twitter: '@learnwithparam',
    github: 'Param-Harrison'
  },
  articles: [
    {
      title: 'How useEffect works?'
    },
    {
      title: 'How useState works?'
    }
  ]
};

Optional chaining is used to safely check whether JS objects contain the value. If not, then it will safely return undefined. This way, the code won't fail due to TypeError.

With optional chaining, you can easily check whether a value exists in the object.

console.log(author?.firstName); // Param
console.log(author?.social?.url); // https://jsmates.com
console.log(author?.social?.facebook); // undefined
console.log(author?.articles?.[0]?.title); // How useEffect works?
console.log(author?.articles?.[3]?.title); // undefined

The syntax for optional chaining is ?.. It works for both arrays and objects. You can see, we checked the articles array inside the author object.

If we have to do the same checking without optional chaining, it will be more verbose,

if (author) {
  console.log(author.firstName); // Param
}
if (author && author.social) {
  console.log(author.social.url); // https://jsmates.com
  console.log(author.social.facebook); // undefined
}
if (author && author.articles && author.articles.length > 0) {
  console.log(author.articles[0].title); // How useEffect works?
}
if (author && author.articles && author.articles.length > 3) {
  console.log(author.articles[3].title);
}

You can play around with the example in the codesandbox.