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
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;23if(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;23// now if data is 0 counter value is 04// if it is null or undefined we set it to 1;
So only if the value is
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;23// here even if the value is 0, that is the value is defined4// we still get 1, which we don't want.
To recap “Nullish coalescing” is essentially
1a ?? b2 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