This website collects cookies to deliver better user experience
JavaScript Quick Tip: The Nullish Coalescing Operator
JavaScript Quick Tip: The Nullish Coalescing Operator
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:
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: