Optional Chaining

Image taken from Unsplash

Optional Chaining


To use optional chaining you will need an Object. This operator can access nested Object properties and it will return undefined if the property doesn’t exist (undefined or null).

With optional chaining, we don’t need to manually check if each property is valid.

Here, we want to check several properties in menu Object.

const menu = {
  breakfast: 'nasi goreng',
  lunch: ['ayam goreng', 'pecel', 'es teh tawar'],
  snacks: {
    one: 'chiki',
    two: 'kopi kenangan'
  },
  countPrice() {
    return 'total 57000';
  }
}

console.log('dinner:', menu?.dinner); // "dinner:" undefined
console.log('snack 2:', menu?.snacks?.two); // "snack 2:" "kopi kenangan"
console.log(menu.countPrice?.()); // "total 57000"

Optional chaining is usually combined with Nullish Coalescing.

Optional Chaining is a new feature in ES2020.