Optional Chaining with Arrays
You'll learn how to safely access array elements when the array itself might not exist.
The Core Idea
Just like you can use ?. to safely access object properties, you can use ?.[index] to safely access array elements. This is crucial when you're not certain whether the array itself is defined or if it might be null or undefined.
The syntax looks like this: arr?.[0] — if arr is nullish (null or undefined), the entire expression returns undefined instead of throwing an error.
Why This Matters
Imagine you're fetching data from an API and expecting an array of users, but sometimes the API returns null for that field. Without optional chaining, you'd need explicit checks:
const users = getUsersFromAPI(); // might return null
// Old way: verbose and repetitive
const firstUser = users && users[0];
// With optional chaining: clean and safe
const firstUser = users?.[0];
If users is null or undefined, users?.[0] simply returns undefined without throwing an error.
Combining with Property Access
You can chain further after the array access:
const data = { items: [{ name: 'Apple' }, { name: 'Banana' }] };
// Safe access through the whole chain
const firstItemName = data.items?.[0]?.name; // 'Apple'
const missingData = null;
const safeName = missingData?.items?.[0]?.name; // undefined (no error!)
This reads left to right: "If data.items exists, try accessing index 0. If that exists, try accessing the name property."
Key Takeaway: Use arr?.[index] whenever you need to access array elements but can't guarantee the array itself exists — it's cleaner and safer than manual null checks.