المعرفة:: JavaScript الحالة::مؤرشفة المراجع:: The Complete JavaScript Course 2022 From Zero to Expert


  • Optional Chaining, introduced in ES2020, simply provides a way to access object properties and methods safely when that property value doesn’t exist (nullish values).
  • If the property before the ? exist, the value of the property before the ? will be read. If it is either zero or a string, undefined is returned immediately to avoid TypeError: can't read property of undefined.
  • Before Optional Chaining, we had to use if checks to ensure the object has the property before getting its value.
if (restaurant.openingHours && restaurant.openingHours.mon) console.log(restaurant.openingHours.mon.open);
 
// WITH optional chaining
console.log(restaurant.openingHours.mon?.open);
console.log(restaurant.openingHours?.mon?.open);

Examples

  • Access day property dynamically, then open property with optional chaining, and at the same time use Nullish Coalescing Operator to set a default value.
// Example
const days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
for (const day of days) {
  // Access day property dynamically
  const open = restaurant.openingHours[day]?.open ?? "closed";
  console.log(`On ${day}, we open at ${open}`);
}
// Methods
console.log(restaurant.order?.(0, 1) ?? "Method does not exist");
console.log(restaurant.orderRisotto?.(0, 1) ?? "Method does not exist");
  • With arrays.
// Arrays
const users = [{ name: "Jonas", email: "[email protected]" }];
// With Optional Chaining
console.log(users[0]?.name ?? "User array empty");
// const users = [];
// Without
if (users.length > 0) console.log(users[0].name);
else console.log("user array empty");