The nullish coalescing operator (??
) is a powerful JavaScript feature that helps you handle null and undefined values more elegantly. If you've been writing JavaScript for a while, you've likely encountered situations where you need to provide fallback values when dealing with potentially null or undefined variables. Let's explore how this operator works and why it's superior to alternatives in many scenarios.
What is the Nullish Coalescing Operator?
Introduced in ECMAScript 2020 (ES11), the nullish coalescing operator (??
) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined. Otherwise, it returns the left-hand side operand.
Here's the basic syntax:
const result = leftExpr ?? rightExpr;
This might seem similar to the logical OR operator (||
), but there's a crucial difference that makes ??
much more useful in certain situations.
Nullish Coalescing vs. Logical OR
Before the nullish coalescing operator, developers commonly used the logical OR operator (||
) to provide default values:
// Using logical OR
const userPreference = userSettings.theme || 'dark';
The problem with ||
is that it checks for "falsy" values, not just null or undefined. In JavaScript, falsy values include:
false
0
''
(empty string)null
undefined
NaN
This behavior can lead to unexpected results. For example, if a user explicitly sets their theme preference to an empty string or the number 0, the logical OR would ignore that choice and use the default value instead.
The nullish coalescing operator solves this problem by only checking for null or undefined:
// Using nullish coalescing
const userPreference = userSettings.theme ?? 'dark';
Now, if userSettings.theme
is an empty string or 0, that value will be respected rather than replaced with the default.
Practical Examples
Form Inputs with Zero Values
When working with form inputs that accept numeric values, the nullish coalescing operator shines:
function processQuantity(quantity) {
// With ||, a quantity of 0 would become 1
// const qty = quantity || 1;
// With ??, a quantity of 0 is respected
const qty = quantity ?? 1;
return qty;
}
API Responses with Empty Strings
When handling API responses, empty strings might be valid data:
function displayUsername(user) {
// With ||, an empty username would show "Guest"
// const displayName = user.username || "Guest";
// With ??, empty usernames are displayed as provided
const displayName = user.username ?? "Guest";
return displayName;
}
Configuration with Boolean Flags
For configuration objects with boolean settings:
function initializeApp(config) {
const showNotifications = config.notifications ?? true;
// With ||, false would be treated as "not provided" and default to true
// With ??, false is respected as the user's explicit choice
}
Chaining the Nullish Coalescing Operator
You can chain the nullish coalescing operator to check multiple potential values:
const result = value1 ?? value2 ?? value3 ?? defaultValue;
This will return the first non-null, non-undefined value in the chain.
Combining with Optional Chaining
The nullish coalescing operator pairs perfectly with optional chaining (?.
):
const userDisplayName = user?.profile?.displayName ?? 'Anonymous';
This combination allows you to safely access deeply nested properties without worrying about errors if any part of the chain is null or undefined.
Browser Compatibility
The nullish coalescing operator is supported in all modern browsers, including:
- Chrome 80+
- Firefox 72+
- Safari 13.1+
- Edge 80+
For older browsers, you'll need to use a transpiler like Babel to convert this syntax to equivalent code that works in those environments.
When to Use Nullish Coalescing
Use the nullish coalescing operator when:
- You want to provide a default value only when a variable is null or undefined
- You need to respect falsy values like empty strings, 0, or false as valid user inputs
- You're working with form data or API responses where empty values might be meaningful
Conclusion
The nullish coalescing operator is a small but significant addition to JavaScript that helps write more predictable code when dealing with potentially missing values. By specifically targeting null and undefined rather than all falsy values, it respects user choices and data integrity in ways that the logical OR operator cannot.
Next time you reach for the logical OR operator to provide a default value, consider whether the nullish coalescing operator might be a better fit for your use case. Your future self (and your users) will thank you for the added precision in handling their data.