How to safely read a nested property
Short answer
The ?. operator stops and returns undefined if the part to the left is null or undefined:
const user = { name: 'Anna' };
console.log(user.address?.city);Output:
undefinedA default value
Add ?? to get a value instead of undefined:
const user = { name: 'Anna' };
console.log(user.address?.city ?? 'unknown');Output:
unknownArrays and methods
?. also works before square brackets and before calling a function:
const order = { items: [] };
const settings = {};
console.log(order.items?.[0]?.title ?? 'no items');
console.log(settings.onSave?.() ?? 'no handler');Output:
no items
no handlerCommon mistake
Without ?. reading a property of undefined throws an error and stops the program:
const user = { name: 'Anna' };
try {
console.log(user.address.city);
} catch (error) {
console.log(error.message);
}Output:
Cannot read properties of undefined (reading 'city')Functions used in this recipe
- Optional chaining (?.) — Safe property access: returns undefined instead of an error if the object is missing.
- Nullish coalescing (??) — Returns the right-hand value if the left is null or undefined.