Optional chaining

Optional chaining (?.)

Published 2021-06-08

Optional chaining (?.)

With the optional chaining operator you can read the value of a property of an object without having to check that the reference is valid.

If the value don't exist, it will return 'undefined' instead of a TypeError.

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog.name;
console.log(dogName);
// TypeError: Cannot read property 'name' of undefined

const fishName = adventurer.fish?.name;
console.log(fishName);
// undefined

Related Tutorials :