Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

undefined

A default value

Add ?? to get a value instead of undefined:

const user = { name: 'Anna' };
 
console.log(user.address?.city ?? 'unknown');

Output:

unknown

Arrays 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 handler

Common 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

Thanks for reading!

Donate to the site — we work hard for you.