DEV Community

Cover image for Optional Chaining Operator
Aaron Goldsmith
Aaron Goldsmith

Posted on

Optional Chaining Operator

The optional chaining operator ?. is a new Javascript language feature introduced in ES2020. It provides a way to access nested object properties without having to expressly validate that each reference in the chain is valid.

The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is null or undefined, the expression returns a value of undefined. When used with function calls, it returns undefined if the given function does not exist.

For example:

const obj = {
  prop1: {
    prop2: {
      prop3: "value"
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

If you attempted access a property in the above object that didn't exist: obj.prop2.prop3 that would throw the following error:

Uncaught TypeError: Cannot read property 'prop3' of undefined

Typically, you could try to handle the case of potentially missing property by combining logical operators and a ternary expression:

const myProp3 = obj.prop2 && obj.prop2.prop3 ? obj.prop2.prop3 : undefined;
Enter fullscreen mode Exit fullscreen mode

This verbose syntax can be written instead using the optional chaining operator which will automatically assign the value of myProp3 to undefined:

const myProp3 = obj.prop2?.prop3; //undefined
Enter fullscreen mode Exit fullscreen mode

For dealing with even more deeply nested objects, the optional chaining operator can be used multiple times in the same statement to safely accommodate the accessing of properties:

let temp = obj.first?.second?.third?.value;

It can also be used with function calls to make sure a function exists, and if it doesn't will return undefined:

let data = obj.someMethod?.(someArgument); //undefined

It can also be used with arrays:

const arr = [5,6,7,8];

arr?.[10] // undefined
Enter fullscreen mode Exit fullscreen mode

With the Map data structure:

let myMap = new Map();
myMap.set("foo", {name: "baz", desc: "inga"});

let nameBar = myMap.get("bar")?.name;
Enter fullscreen mode Exit fullscreen mode

And finally, with the nullish coalescing operator ??:

const myCar = {
  make: "Ford",
  details: { year: 1982 }
};
const customerCar = myCar?.make ?? "Unknown Car";
console.log(customerCity); // Unknown Car
Enter fullscreen mode Exit fullscreen mode

Top comments (0)