Nullish Coalescing for JavaScript

29 November 2019 — Written by Amit Solanki
#javascript

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

let counter;

if(response.data === null) counter = 1;
else 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.


let counter = response.data ?? 1;

// now if data is 0 counter value is 0
// 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.

result = actualValue ?? defaultValue

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

let counter = response.data || 1;

// here even if the value is 0, that is the value is defined
// we still get 1, which we don't want.

To recap "Nullish coalescing" is essentially

  a ?? b
  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

Amit Solanki