Press enter to see results or esc to cancel.

OPTIONAL CHAINING OPERATOR IN JAVASCRIPT

OPTIONAL CHAINING OPERATOR is a very new operator in javascript introduced in 2020

It was proposed back in 2019, and everyone was waiting for it to be launched finally with ES2020 we can use this operator and it is extremely helpful

Optional chaining is a very handy operator, and it was very much needed,
It has become one of my favourite operators too, and by the end of this post, it will be your’s favourite too!

WHAT IS OPTIONAL CHAINING OPERATOR?

OR

HOW TO USE OPTIONAL CHAINING OPERATOR IN JAVASCRIPT?

Optional chaining operator is an extremely useful life-saving operator it provides a way to simplify accessing values through connected objects when it’s possible that a reference or function maybe undefined or null.

SYNTAX:

 object?.data 
 object?.['data'] 
 array?.[index] 
 function?.(arguments)

Let’s consider a nested user object obj that has nested sub-properties and we are not sure if we will receive the data or null/undefined values

If we don’t have optional chaining operator we have to validate this with AND logical operator such as:-

let user ={}
//We received a empty user object, 
let img = user.profile.img 
//Uncaught TypeError: 
//  Cannot read property 'img' of undefined

The above code will throw an error because property profile is undefined.
So to avoid errors we do it this way (the old way):-

//VALIDATING EACH PROPERTY EXIST
let hasImg= user && user.profile && user.profile.img;
//expected result: undefined

The code above works & looks fine but if you have a really big nested object it will be a real pain to check each property exist and your code will also extend to additional lines just because of this.

Here come’s the life-saving operator, This is how you do it with Optional Chaining operator easy, fast, beautiful & less code:-

let userImg = user?.profile?.img
//expected result: undefined

If we directly try to access img from user object like this user.profile.img it will throw an error because profile is undefined and we are trying to access sub-property img of undefined just like: undefined.img and it will through an error but with chaining operator, if left-hand property is undefined it will return undefined due to which our Application won’t crash as there will be no errors!.

BROWSER COMPATIBILITY:

Optional Chaining Operator in javascript is still in development and it is not yet compatible on all browsers and is not recommended to be used in production

,JAVASCRIPT OPTIONAL CHAINING OPERATOR’s BROWSER COMPATIBILITY

Implementation Progress:

Optional Chaining Operator has not yet reached cross-browser stability, It is still not fully compatible with all javascript engines.

Here’s the daily implementation of Optional Chaining Operator showing implementations on various javascript engines, this information is updated on daily bases by Test262:

More Articles:

9

SELECT
LANGUAGE

Send this to a friend