Back to all posts

Javascript optional chaining (?.)

Deeper dive in optional chaining

What is Optional Chaining (?.)

Optional chaining, introduced in ECMAScript 2020, is a feature that simplifies the process of accessing properties and methods of nested objects or arrays when intermediate properties may be null or undefined.

How to Access Nested Properties

In this example, we have a JavaScript object representing a user with nested address information.

const user = {
    name:"John",
    address:{

    }
}

Traditional Approach

The traditional way to call the getAddress() method and access the city property involves additional checks to ensure that the method exists and returns a non-null value.

let city;
if(user && user.getAddress){
    const address = user.getAddress();
    if(address){
        city = address.city;
    }
}

console.log("Traditional Approach:",city); // Output: San Francisco

This code first checks if the user object exists and if it has a getAddress method. Then it calls the method and checks if the returned address object exists before accessing its city property.

Optional Chaining

With optional chaining, calling the nested method and accessing the city property can be done in a more concise manner:

const city = user?.getAddress?.().city || "Unknown";

console.log("Optional Chaining Approach:",city); // Output: San Francisco