Getting Property Value in a Deeply Nested Object (using ES2020 Optional Chaining Operator)

javascript
Published on May 4, 2020

The Optional Chaining Operator, introduced in ES2020, makes it very easy to get value of a property in a deeply nested Javascript object.

Previously finding value of a property in a chain of connected objects involved checking all intermediate properties in the chain (whether they existed), and then finally getting the value of the intended property.

let person = {
	name: "John Doe",
	id: 34344,
	details: {
		address: {
			street: "232 XXX Lane",
			zip: "343435",
			city: "Bangalore"
		}
	}
};

let city;

// checking for all intermediate properties
if(person.details && person.details.address && person.details.address.city)
	city = person.details.address.city;

However the Optional Chaining operator denoted by ?. makes this step very simple. Using this operator there is no need to check whether intermediate properties are existing or not.

The same thing achieved with the Optional Chaining operator :

let city = person.details ?. address ?. city;

If any intermediate property is nullish (either null or undefined), the expression returns undefined.

// undefined as person.details.tax does not exist
let city = person.details ?. tax ?. social_id;
// undefined as person.details.address.landmark does not exist
let city = person.details ?. address ?. landmark;

Browser Compatibility

Optional Chaining operator is supported in all current versions of Chrome, Firefox, Edge & Safari.

In this Tutorial