Navigate back to the homepage

Nullish Coalescing for JavaScript

Amit Solanki
November 29th, 2019 · 1 min read

Nullish Coalescing proposal has been moved to stage 3, i.e. soon it will be added to JS standards, let’s see how it helps us.

How many times have you checked whether a variable is null or not? Not undefined, '' or false but just null, I would typically add an if condition variable === null just for that, and I’ve done this countless number of times.

Consider the following code

1let counter;
2
3if(response.data === null) counter = 1;
4else counter = response.data;

What if we could do this easily without so much code to just check if it is null or not. Nullish coalescing just does that. Here’s how it looks and works.

1let counter = response.data ?? 1;
2
3// now if data is 0 counter value is 0
4// if it is null or undefined we set it to 1;

So only if the value is undefined or null then the default value will be used.

1result = actualValue ?? defaultValue

Let’s see what we would get when we use the logical OR operator.

1let counter = response.data || 1;
2
3// here even if the value is 0, that is the value is defined
4// we still get 1, which we don't want.

To recap “Nullish coalescing” is essentially

1a ?? b
2 a !== undefined && a !== null ? a : b

Current status and how to use

You can check the ECMAScript Next compatibility table to find out where the ?? operator is supported. Babel has the plugin @babel/plugin-proposal-nullish-coalescing-operator

More articles from Amit Solanki

Handling CORS in Rails for client side apps

Handling CORS in Rails for JS apps using React, etc

January 20th, 2019 · 1 min read

How to setup PostgreSQL on MacOS

PostgreSQL setup reference

January 13th, 2019 · 1 min read
© 2018–2019 Amit Solanki
Link to $https://twitter.com/iamsolankiamitLink to $https://github.com/iamsolankiamit