The optional-chaining operator

JavaScriptreadability

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!)

More fire tips

Replacing all matches in a string

The String prototype’s replace function only replaces the first occurrence of a substring by default. We can extend that with a global flag on the expression.

JavaScriptregular expressions
Read fire tip

Read all fire tips →