Is there a "null coalescing" operator in JavaScript?
JavaScript now offers the nullish coalescing operator, ??, returning a fallback for null or undefined.
The result is someVal, unless it's null/undefined — then it's 'fallback'.
Please, mind the gap between null and 'fallback'. 🚧 Stay safe!
Deeper Dive: Understanding the Nullish Coalescing Operator
Before ??, || (logical OR) was frequently used for providing defaults. However, || returns the first truthy value which can lead to unexpected results when dealing with falsy values like 0 or "". Let's see with an example:
Demystifying the || Operator
Getting more out of || than just logical OR. Got a minute? Let's dive in.
Here, attemptsBackup unexpectedly jumps to 10, despite attempts's legitimate 0. You see the issue here, right?
Nullish Coalescing for Precise Default Values
It's time for ?? to shine for better precision:
Now, attemptsBackup doesn't lose the plot and correctly falls back to 0.
Building Smarter Fallbacks
When you want to provide defaults only for null and undefined, a custom coalesce() function lights the way.
Delving Deeper with Optional Chaining
Combine optional chaining and nullish coalescing for deep dive checks:
You could call it an undercover mission, and ?. your best secret agent. Shhh!
You Might Wonder: Handling Edge Cases
Sometimes, falsy but valid values can trick || because it's so fast, it sometimes overlooks details! Let's look at an example:
False-y but True
Here, message is a valid empty string, but || misses it. Time for specific null checks!
Tailored Null Coalescing Functions
Bespoke $N function can look for null or undefined only:
Spare No Effort for Assurance: Testing!
Always test your custom functions to avoid unpleasant surprises:
Anyone said Ghostbusters? We have Bugbusters here! 💪
Was this article helpful?