Optional Chaining Operator (?.) in Javascript

Muhammad Faraz Ali
3 min readMar 1, 2024

--

Optional chaining is a powerful feature introduced in ECMAScript 2020 (ES11) that simplifies working with nested object properties and method calls. This operator brings a more concise and safer way to handle optional properties, instead of throwing an error “Cannot read property ‘x’ of undefined”.

Basics of Optional Chaining

Let’s start with the basics. The optional chaining operator allows you to access properties and methods of an object without explicitly checking if each level of the nested structure exists. It short-circuits the evaluation if a property or method is null or undefined, returning undefined instead of throwing an error.

Use-Cases and Examples

1-Objects

object_property

Consider the following user object:

const user = {
name: 'David',
address: {
country:'Australia'
},
};

If you want to access the (nested) property and that property does not exist you will face an error ( “Cannot read property ‘x’ of undefined”).

console.log(user.address.city); //TypeError: Cannot read property 'city' of undefined

Solution1: Traditional approach


const city = user && user.address && user.address.city; //undefined

//or

const city = user.address ? user.address.city : undefined; //undefined

Solution2: With Optional Chaining

const city = user.address?.city; //undefined

2-Function calls

object_method

Optional chaining is handy when calling functions that may not exist.

const user = {
name: 'David',
getAddres:function (){
return {
city: 'Sydney',
country:'Australia'
}
}
};

If you want to access getAddress method.

Traditional Approach:

user && user.getAddress && user.getAddress();

With Optional Chaining:

user.getAddress?.();
user.getAddress?.().city;//If user has address then access user's city

3-Arrays

array

Consider an array of objects representing users and their hobbies:

const users = [
{ id: 1, name: 'Alice', hobbies: ['Reading', 'Writing'] },
{ id: 2, name: 'Bob', hobbies: null },
{ id: 3, name: 'Charlie', hobbies: ['Blogging', 'Cooking'] }
];

Suppose you want to access the hobbies of ‘Bob’.

Traditional Approach:

const secondUserHobbies= users && users[1] && users[1].hobbies; //undefined

Optional Chaining:

const secondUserHobbies= users[1]?.hobbies; // undefined (no error)

const firstUserSecondHobby=users[0]?.hobbies?.[1]; // Writing

4-Combination with Nullish Coalescing (??) operator

Optional chaining operator (?.) which is useful to access a property of an object which may be null or undefined. Combining them, you can safely access a property of an object which may be nullish (null or undefined) and provide a default value if it is.

Optional chaining can be combined with nullish coalescing (??) to provide default/fallback values for null or undefined.

Example1:

const user = {
name: 'David',
address: null,
};

Traditional Approach:

const city = user.address ? user.address.city : 'Sydney';//Sydney

With Optional Chaining:

const city= user.address?.city ?? 'Sydney'; //Sydney

Example2:

const user= { name: "Devin" };

console.log(user.name?.toUpperCase() ?? "not available"); // "DEVIN"
console.log(user.city?.toUpperCase() ?? "not available"); // "not available"

Note: Optional chaining is not valid on the left side of an assignment. It is not used for assignments, it is only used for accessing or reading.

It is invalid to try to assign to the result of an optional chaining expression:

const user= {};
user?.name = 'David'; // SyntaxError: Invalid left-hand side in assignment

Conclusion

The optional chaining operator in JavaScript is a powerful addition that enhances code readability and conciseness, especially when dealing with complex data structures. It makes your codebase more resilient to unexpected null or undefined values. Consider using optional chaining in your projects to write cleaner and safer code.

--

--

Muhammad Faraz Ali

Strong believer, Highly motivated and a self learner Software Engineer. Tech stack: JavaScript, React, Next and React Native.