Maciej Pyrc

Optional Chaining & Nullish Coalescing

The two functionalities of Javascript, which I describe in today’s post, are amazing development enhancers. They offer increased readability and significant simplification of the code in situations when we work with nested data.

Optional Chaining

We call this operator using? On the object to get the value of some key on it. If the object and its key exist, the value we want to read will be returned, but if the object does not exist, the undefined value will be returned without throwing a reference error, so the code will not be interrupted.

It is fantastic quality improvement, especially for nested data, so you do not have to write additional conditions, see for yourself in the example below.

Nullish Coalescing

This is an operator whose calling is similar to the logical operator OR or ||, we call it with? in conditions.

Fulfilling this condition requires passing null or undefined to the left side of it. It’s beneficial in many cases, so we can often get rid of a lot of the code easily while increasing overall readability. It is most useful when you want to use the value 0 in the condition so that it is not the default false.

Availability and implementation

There are several possibilities to use the mentioned functionalities. They are currently being deployed to browsers and are also not natively available for Node.js.

For production use, it’s best to use Babel presets or use Typescript. The differences can be seen in the bundle size, which in the case of Babel is smaller.

Additional sources:

@babel/plugin-proposal-optional-chaining

@babel/plugin-proposal-nullish-coalescing-operator

Do you like this article? Share it with your friends:
Author:

Maciej Pyrc

Write to me: m.pyrc@gmihub.com

Recommended articles

Build your product with GMI

Send us an inquiry and get the answer at the same day!

Hire Us