💻 Tech
Optional chaining also works with accessing an index of an array. With x?.[0], we’re safely accessing the value of an element, so we can handle if it’s undefined; otherwise, we will get an error like this: TypeError: Cannot read properties of undefined (reading '0').
const a = {};
const b = { x: undefined };
const c = { x: [] };
const d = { x: [1] };
console.log(a?.x?.[0] ?? "x property doesn't exist");
console.log(b?.x?.[0] ?? "x is undefined");
console.log(c?.x?.[0] ?? "x is empty");
console.log(d?.x?.[1] ?? "x has 1 element");
/* Output:
x property doesn't exist
x is undefined
x is empty
x has 1 element
*/