🍏Optional Chaining

In JavaScript, optional chaining is a feature that allows you to access an object's properties or methods without having to check if the object is null or undefined. It allows you to safely access a chain of properties that may not exist, without having to check for the existence of each one.

For example, suppose you have an object with several nested properties, and you want to access the value of a property that is several levels deep. Without optional chaining, you would have to check whether each object in the chain is null or undefined before accessing the next one, like this:

let obj = {
  a: {
    b: {
      c: 'hello'
    }
  }
};

let value;
if (obj && obj.a && obj.a.b && obj.a.b.c) {
  value = obj.a.b.c;
}

console.log(value); // 'hello'

With optional chaining, you can simplify this process by using the ?. operator to access the properties in the chain. If any property in the chain is null or undefined, the expression will return undefined instead of throwing an error:

let value = obj?.a?.b?.c;

console.log(value); // 'hello'

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

let obj = {
  a: {
    b: {
      c: () => 'hello'
    }
  }
};

let value = obj?.a?.b?.c();

console.log(value); // 'hello'

In summary, optional chaining is a useful feature in JavaScript that allows you to safely access nested properties or methods of an object without having to manually check for null or undefined values.

Last updated