Nested optional chaining in JavaScript

You can use JavaScript’s optional chaining operator multiple times within a statement. That is useful if you need to access nested properties which may not exist.

const people = [
  {
    name: 'John',
  },
  {
    name: 'Jack',
    favoriteFilm: {
      title: 'Goodfellas',
    },
  },
  {
    name: 'Jane',
    favoriteFilm: {
      title: 'Monsters, Inc.',
      tagline: 'We scare because we care.',
    },
  },
]

Here we retrieve the tagline without first checking that every antecedent property exists.

const mapped = people.map(person => ({
  name: person.name,
  tagline: person?.favoriteFilm?.tagline
})

Sign up for my newsletter

A monthly round-up of blog posts, projects, and internet oddments.