Love Frontend
Community of frontend developers
RU

Optional Chaining [ru]

Author: qubal
Publication date: 22.04.2020

The only good thing about 2020 - is new ES standart, that brought us OptionalChaining operator, which is supported natively by only V8 engine. But! Babel is already able to transpile ES20 to ES6. And many developers are happy to use optional chaining in their projects.

So, lets learn new feature by doing. Learning new things is never late!

 const fetchedData = {
countries: {
Angola: {
value: 1032,
},
Russia: {
value: 23041,
},
Germany: {
value: 12313,
},
},
};

fetchedData repesents an object you usually get from an API. Lets imagine that something went wrong and we've recieved our data damaged.

const fetchedData = {
countries: {
Angola: {
value: 1032,
},
Russia: {},
},
};

When we will try to acces field "value" of object "Russia", we will face Uncaught TypeError: Cannot read property 'value' of undefined. To escape it you have to write a ton of code.

const russianValue = fetchedData &&
fetchedData.countries &&
fetchedData.countries.Russia &&
fetchedData.countries.Russia.value;
console.log(russianValue); //russianValue

I hate that type of constructions, they are big, ugly, and dont have magic in them. That's when we use our optional chaining operators, that make our code *COOLER*.

const russianValue = fetchedData?.countries?.Russia?.value;
console.log(rusiianValue); //undefined

Eric Napierała's test show that transpiled code, written with use of optional chainin is being parsed 1ms longer than native js code. Is it big difference? In case you have ten thousand of optional chains for the whole project - yes, otherwise - you don't have to worry about it.

Runtime perfomance of optional chaining can't upset you. When you use string arrays optional chaining improves your perfomance to 600%, when you replace external libraries with oc - you speed your projects up to 3000%, because methods, that don't use acccessors functions are more effective.

It's nice to know, that standart is always striving and prospering, bringing something new to JS ecosystem, yet letting coders use old. Optional chaining eases your life, but doesn't solve all of the problems. I will leave you a right of choice: whether to use optional chaining or not

Enter your email to subscribe on news