The optional-chaining operator

We can get nested values from objects by chaining their keys. We run into an error when we try to get a value from something that does not exist. With optional chaining, these calls return undefined instead of throwing errors.

// this person’s address is nested in the outer object as another object
const mario = {
  occupation: 'Plumber',
  address: {
    street: 'Rainbow Road',
    zip: '81664'
  }
}

// we can get the full address, or drill into it to get the street
mario.address         // ⇒ { street: 'Rainbow Road': zip: '81664' }
mario.address.street  // ⇒ 'Rainbow Road'

// we don’t have a nested address for this person
const toad = {
  occupation: 'Explorer'
}

// if we try to get the street, JavaScript will throw an error
toad.address         // ⇒ undefined
toad.address.street  // TypeError: undefined is not an object

// the ?. operator returns `undefined` if it hits any undefined value
toad?.address          // ⇒ undefined (same as without the questionmark)
toad?.address?.street  // ⇒ undefined (no error!)

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.