How To Use Optional Chaining In JavaScript

In this post, we're going to understand how we can use the optional chaining feature in JavaScript to check bullish values while trying to access object properties. Optional chaining is a feature in JavaScript that allows you to access an object's properties, methods, or elements without having to worry about whether the object is null or undefined. This can be useful when working with data that may not always be present, or when working with deeply nested objects where it is not always clear if all the intermediate properties exist.

Let's understand this in detail using an example,

const user = {
  name: 'John Doe',
  age: 25,
  address: {
    street: 'Queen Street',
    city: 'Calgary',
    country: 'Canada'
  }
};
console.log(user.address.country); // Outputs: Canada

In this example, we have an object called user with several properties, including the address property that is itself an object. We can access the country property of the address object using dot notation.

Now, consider what happens if the address property is not present on the user object,

const user = {
  name: 'John Doe',
  age: 25
};
console.log(user.address.country); // Outputs: "TypeError: Cannot read property 'country' of undefined"

In this case, we get a TypeError because we are trying to access a property of undefined. This can be a problem if we are not sure whether the address property will always be present on the user object.

Optional chaining allows us to avoid this problem by allowing us to "chain" together object accesses and method calls, but short-circuit the chain if any part of it is null or undefined.

Here is an example of how we can use optional chaining to safely access the country property of the address object,

const user = {
  name: 'John Doe',
  age: 25
};
console.log(user?.address?.country); // Outputs: undefined

In this case, the optional chaining operator (?.) will short-circuit the chain if the address property is not present on the user object, and the result will be undefined rather than a TypeError.

Optional chaining can also be used to call methods on an object, like so,

const user = {
  name: 'John Doe',
  age: 25,
  sayHello() {
    console.log(`Hey there, I am ${this.name}`);
  }
};
user?.sayHello(); // Outputs: "Hey there, I am John Doe"
const empty = null;
empty?.sayHello(); // Does nothing (the method is not called)

Optional chaining is a useful feature that can help you write more robust and reliable code when working with data that may not always be present or fully initialized. It is especially useful when working with deeply nested objects or when dealing with asynchronous data that may not be available immediately. 

And that's it! I hope you enjoyed this post. In case you have any query or feedback, feel free to drop a comment.