DEV Community

Cover image for ⚡️JavaScript Optional Chaining (?.)
Ahmed Murtaza
Ahmed Murtaza

Posted on

⚡️JavaScript Optional Chaining (?.)

Optional chaining allows us to safely read the value of each deeply nested property within an object (or chained objects) without the need to separately evaluate the existence of each property.

For newbies, it might not touch them deeply, but optional chaining solves a great deal of errors JavaScript developers face very frequently.

📌Example #1:

Consider a user object, which is supposed to have user relevant details as properties:

Let user = {
   name: ‘John Doe’, 
   email: john@doe.com
};
Enter fullscreen mode Exit fullscreen mode

Consider you try to access user.address.postcode, which will eventually give “Cannot read property of undefined..” Error. It’s because address is undefined and attempt to get user.address.postcode fails with an error as undefined doesn’t have Object like properties.

📌Example #2:

In web application we access DOM elements, such as, document.querySelector(‘#heading’), and can access its properties or manipulate content using document.querySelector(‘#heading’).innerText. Now In-case document.querySelector(‘#heading’) didn’t return any element instead undefined, it will again fail and show same ‘non-existing property’ error.

🌟Introducing Optional Chaining (?.):

Optional chaining helps us by not showing an Error in-case there is nullish (null or undefined) property before ?. operator and return undefined without further evaluation.

In other words:

  1. user?.address?.postcode will return undefined if address is undefined instead of throwing an Error.
  2. It greatly helps to reduce multiple conditions evaluating each nested property whether they are nullish or not.

Top comments (0)