JavaScript Quick Tip: The Nullish Coalescing Operator
How to more effectively filter out null and undefined
Have you ever written code like this?
const result = a || b;
It works pretty well until it doesn't.
Using the logical OR to get a value or a fallback works 90% of the time you use it. But the other 10% are actually when you hit falsy values, which might otherwise be perfectly valid.
One point you can usually see such code at is the beginning of functions that don't use default parameters, like seen here:
const myFunction = (parameter) => {
const cleanedParameter = parameter || 'a default value';
// ... more code ...
}
If you call it like this:
myFunction();
or like this:
myFunction(null);
it works perfectly fine.
But what if the following call was actually a valid one?
myFunction('');
Well, the empty string is a falsy value and will thus be replaced with the default value. And this is where you hit the 10% where the logical OR doesn't help you anymore.
Enter The Nullish Coalescing Operator
The nullish coalescing operator works nearly identical to the logical OR, but it only reacts to null and undefined. Instead of two pipes, you place two question marks, and it looks like below:
const result = a ?? b;
If you now replace the logical OR in your function with the nullish coalescing operator like this:
const myFunction = (parameter) => {
const cleanedParameter = parameter ?? 'a default value';
// ... more code ...
}
making the same call with the empty string as before:
myFunction('');
will lead to the empty string being treated as a valid value again.
No matter what falsy value you pass from now on, be it the empty string, the number 0, or else, only null and undefined will be treated.
The Whole Tip As An Image
If you like visual content more, or if you want to store it for later, I put all this into one single image for you. I hope you like it!
Before You Leave
If you would love to read even more content like this, feel free to visit me on Twitter or LinkedIn.
I'd love to count you as my ever-growing group of awesome friends!