UI Development, Uncategorized

Optional Chaining for better readability

If you are a frontend developer, I am sure you must have faced one or two bugs related to deep checking keys in an object. For the same reason we use the following code while creating global objects.
let Global_USER = Global_USER || {};
let Global_USER.age = Global_USER.age || 20;
And in most cases our errors would have been cannot find age of undefined  if Global_USER  never existed.

So we have tried fixing this problem with conditional statements

let isAdult = false;
if (Global_USER) {
    If (Global_USER.member) {
        If (Global_USER.member.age) {
        		isAdult = Global_USER.member.age > 18;
    	}
    }
}
We have done the same with querySelectors() .
let el = document.querySelector('.fancy-classname');
if (el) {
	el.classlist.add('is-in-use');
}
But that consumes a lot of development time and lines of code. Hence the concept of Optional Changing[2] was considered in browsers and implemented in Chrome browser[1].

 

What is Optional Chaining?

Optional Chaining provides safe access to inner objects of a JSON object in such a way that if it doesn’t exist, then instead of breaking the page, it would return undefined .
This is how it works. If you want to see if an object exists or not, you can always use a ?  right after it. This makes it safely access deep object without throwing any errors.

Let’s take a look at our previous example again, but this time with the help of optional chaining.

let isAdult = Global_USER?.member?.age > 18; // returns true;
let name = Global_USER?.member?.name; // returns undefined
As of now, this specification is available in Chrome Canary and will be available in Chrome 80. But other browser manufacturers will be implementing it soon as well.

 

References

 

About The Author