Optional Chaining

Optional Chaining (?.)

Example

?. stops and returns undefined when the value before it is null or undefined, instead of throwing:

const order = { customer: { name: "Asha" } };
console.log(order.customer?.name);
console.log(order.shipping?.address?.city);
console.log(order.getTotal?.());           // call only if it exists
console.log(order.items?.[0] ?? "no items");

Output

Asha
undefined
undefined
no items

Without It

Example (error)

const order = {};
console.log(order.shipping.address);

Output

Uncaught TypeError: Cannot read properties of undefined (reading 'address')