Level Up Your JavaScript Code with Optional Chaining Operator

Property Chaining Challenges

When working with JSON structures in JavaScript, accessing nested properties and verifying whether a given value exists or not can be challenging. It often leads to a lot of conditional checks and multiple AND operators (&&) to prevent errors such as “TypeError: Cannot read property ‘********’ of undefined”. One way to address this is to use the && operator as a fallback option, which assigns a null value to the variable if the object property is null or undefined.

So, in JavaScript, we use the && operator as a fallback option.

The coolest thing about this operator is that the second expression will never be executed if the first expression is false. For example, to check if a car object is defined before using it, we can use the following code:

const candidate = { company: “Mindbowser”}
const company = candidate && candidate.company;

Even if the car is null, we don’t get errors and the color is assigned a null value.

However, when dealing with complex object structures with multiple nested properties, such as:

const colorVariable= { }
const colorName =colorVariable && colorVariable.color && colorVariable.color.name;

In other programming languages, we use the && operator to determine true or false,since it’s a logical operator. But in JavaScript, it allows us to do some really amazing things.

In Javascript, everything is treated as an object and an object can have a very different nested structure of objects.

Let’s take one more example

Objects can have different set of properties during runtime:

//1st 
const obj = {
user: {
//..
user2: {
//..
value: 'Some value'
}
}
};

//2nd
const obj ={
user: {
//nothing here
}
};

Therefore, we have to manually check the property’s existence:

if(obj && obj.user != null && obj.user.user2 != null){
let result = obj.user.user2.value)
}

So, we can see that there’s a lot of overlapping code in the above example.The code currently includes multiple conditional statements to perform checks on each field of a JSON object.Thats where the optional chaining feature of JavaScript comes into the picture.

Manually checking each property’s existence becomes tedious. That’s where the optional chaining feature of JavaScript, introduced in ES2020, comes in.

Unlock the Power of Java: Hire Our Expert Developer Today!

What is Optional Chaining?

Optional chaining is a feature of ES2020 that allows us to check if an object exists before trying to access its properties.If any of the values after the ‘?’ operator are null or undefined, the statement will return null or undefined without throwing an error.

“?.” is used as an optional chaining operator.

syntax

obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)

Let’s see how to handle multiple ways of accessing the properties of an object

let city = users && users.address && users.address.city

We can rewrite the above line as

let city = users?.address?.city

So,the basic rule is if any of the values after a ‘?’ are nullish or undefined, then the statement will return either null or undefined without throwing an error.

An alternative for not repeatedly adding the ‘?’ operator at every level provided we are confident that every user has an address but uncertain if the users exists is

let city = users?.address.city

We need to check the existence of objects or arrays prior in order to access its properties and if while iterating over an array too.

e.g:

const data= [ ];

data.map( ( item, index )=> {
return item;

});

What if the data variable is null or undefined?

=> We would get an error i.e Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

The quick solution to this is to check whether our data exists and this can be determined by checking the array.length.

const data = ["user"];
    if(data && data.length > 0){
data.map(item => item)
}

Or,

const data = [“user”];
data && data.length > 0 && data.map( item => item )

We can improve this piece of code with a simple question mark

data?.map( item => item)

Let’s take one more example

let company = {
name: "Mindbowser",
revenue: 2000,
users: [
{ name: "Deepak", email: "deepak@mindbowser.com" },
{ name: "Devashree", email: "devashree@mindbowser.com" },
],

getUserName: () => {
return company.users.map(user => user.name);
},
};

// Call the getUserName method and store the returned value in a variable
let userNames = company.getUserName();

In order to access the values of this object and the object can be undefined or null

const companyName = company !== undefined && company !== null ? company.name : undefined;

Using optional chaining we can

const companyName = company?.name

When we use optional chaining with function calls and the method is not found, the expression evaluates to undefined instead of throwing an exception, which can help avoid runtime errors.

company.getUserNames?.()
>undefined
coma

Conclusion

Using optional chaining makes the code more organised and readable. It enhances code by handling null or undefined values effectively. It simplifies nested property access and method calls, reducing the risk of errors and improving code readability. By utilising the optional chaining operator, developers can create more resilient and concise code, leading to better-quality JavaScript applications. It also allows us to handle multiple ways of accessing the properties of an object without manually checking each property’s existence.

Keep Reading

Keep Reading

Mindbowser is excited to meet healthcare industry leaders and experts from across the globe. Join us from Feb 25th to 28th, 2024, at ViVE 2024 Los Angeles.

Learn More

Let's create something together!