Explain Codes LogoExplain Codes Logo

Is there a "null coalescing" operator in JavaScript?

javascript
nullish-coalescing
javascript-operators
best-practices
Nikita BarsukovbyNikita BarsukovΒ·Nov 3, 2024
⚑TLDR

JavaScript now offers the nullish coalescing operator, ??, returning a fallback for null or undefined.

let result = someVal ?? 'fallback';

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.

let attempts = 0; let attemptsBackup = attempts || 10; // Unexpected output: 10 instead of 0

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:

let attempts = 0; let attemptsBackup = attempts ?? 10; // Output is 0, as expected

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.

function coalesce(...params) { // It’s like waiting for a bus: First non-null, non-undefined parameter gets on! for (let param of params) { if (param !== null && param !== undefined) return param; } } let result = coalesce(null, 0, 10); // Result: 0, finally!

Delving Deeper with Optional Chaining

Combine optional chaining and nullish coalescing for deep dive checks:

const configuration = { theme: { color: null } }; const color = configuration.theme?.color ?? '#FFFFFF'; // Lucky white color!

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

let message = ""; // Intentionally empty message let messageFallback = message || "Default Message"; // Outputs "Default Message"

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:

function $N(value, fallback) { // Checks only for null or undefined, strictly no bouncers! return (value === null || value === undefined) ? fallback : value; }

Spare No Effort for Assurance: Testing!

Always test your custom functions to avoid unpleasant surprises:

console.assert($N("", "Fallback") === "", "Hey! The string is empty, it's not null!");

Anyone said Ghostbusters? We have Bugbusters here! πŸ’ͺ