The optional-chaining operator

Posted on

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. To avoid that, we had to check if any value along the chain was undefined.

With optional chaining, these calls return those undefined values 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!)
// 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!)
Debug
none
Grid overlay