DEV Community

Cover image for JavaScript Quick Tip: The Nullish Coalescing Operator
Oliver Jumpertz
Oliver Jumpertz

Posted on • Edited on • Originally published at oliverjumpertz.com

JavaScript Quick Tip: The Nullish Coalescing Operator

Have you ever written code like this?

const result = a || b;
Enter fullscreen mode Exit fullscreen mode

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 ...
}
Enter fullscreen mode Exit fullscreen mode

If you call it like this:

myFunction();
Enter fullscreen mode Exit fullscreen mode

or like this:

myFunction(null);
Enter fullscreen mode Exit fullscreen mode

it works perfectly fine.

But what if the following call was actually a valid one?

myFunction('');
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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 ...
}
Enter fullscreen mode Exit fullscreen mode

making the same call with the empty string as before:

myFunction('');
Enter fullscreen mode Exit fullscreen mode

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!

A picture showcasing the above code

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!

Top comments (0)