Sikau

JavaScript Applications · Day 30 · about 20 min

Safe access

Optional chaining and ??.

When data is missing

Data from the internet is often incomplete: a user without an address, a product without a discount. Reading user.address.city when there's no address crashes. Two small operators make missing data safe.

?. optional chaining

const user = { name: "Hari" };

// console.log(user.address.city); // TypeError!
console.log(user.address?.city);
console.log(user.greet?.());
console.log(user.tags?.[0]);

The rest of this lesson

  • ?? a fallback for missing valuesexplain
  • Handling incomplete API dataexplain
  • Predict the outputpredict
  • ?? versus ||predict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap