Understanding JavaScript’s Nullish Coalescing Operator (??)
Published March 28, 2024 at 3:15 am
What is JavaScript’s Nullish Coalescing Operator (??)?
If you’ve stumbled upon the ?? operator in JavaScript and wondered about its purpose, you’re not alone.
Simply put, the nullish coalescing operator is a logical operator that returns its right-hand side operand when its left-hand side operand is either null or undefined, and otherwise returns its left-hand side operand.
This operator can be particularly handy when you have to deal with defaults or fallback values.
TL;DR: Quick Example of Nullish Coalescing Operator in Action
const greeting = user.input ?? 'Hello, guest!';
This single line of code leverages the nullish coalescing operator by checking if user.input is neither null nor undefined. If it’s neither, it uses user.input; otherwise, it falls back to the string 'Hello, guest!'.
Understanding the Nuances of ??
Before the introduction of the nullish coalescing operator, many developers used the logical OR operator (||) for similar purposes.
However, the OR operator has its pitfalls when dealing with falsy values that are still valid, like 0 or an empty string. In contrast, the nullish coalescing operator differentiates between the falsy values and null/undefined.
Pitfalls of Logical OR (||)
Consider the following scenario where user settings can be 0.
const userSettings = userData.settings || 'default settings';
If userData.settings is 0, it’s still a falsy value and the OR operator will undesirably return ‘default settings’. This is not the intended behavior when you actually need to capture 0 as a valid setting.
Correct Use of Nullish Coalescing Operator (??)
To precisely handle such cases, if we replace the OR operator with ??:
const userSettings = userData.settings ?? 'default settings';
Now, if userData.settings is 0, the code correctly interprets 0 as a valid non-nullish value and assigns it to userSettings.
Real-World Examples
Imagine a function that takes an optional parameter and you want to assign a default value only if the argument is null or undefined.
function calculateScore(rawScore) {
return rawScore ?? 50;
}
Here calculateScore function will only assign 50 as the default if rawScore is null or undefined, thus preserving all other falsy but valid scores, such as 0.
Similarly, in component configurations or state initializations, the nullish coalescing operator can safeguard against unintended falsy values:
const appConfig = {
theme: userPreferences.theme ?? 'dark',
pageSize: userPreferences.pageSize ?? 20
};
This code block ensures that user preferences are respected, defaulting to ‘dark’ theme or 20 items per page only when the user hasn’t specified an option.
Comparison with Other Default Value Strategies
Pros of ?? over ||
- Does not confuse falsy values like
0or''(empty string) withnullorundefined. - More explicit intention and readable for setting defaults.
- Prevents bugs where falsy values are valid and should not be replaced with defaults.
Cons of ??
- Relatively new and might not be supported in very old JavaScript environments without a transpiler.
- Cannot be used to catch other falsy values like
false,NaN, or0that you may want to replace with a default value.
Combining Nullish Coalescing with Other Operators
For cases where you may want to apply further operations or checks, JavaScript allows combining the nullish coalescing operator with others elegantly.
let userID = user.id ?? generateID();
console.log(userID > 0 ? `User ID: ${userID}` : 'Invalid ID');
Note that the ternary operator (? :) checks if userID is greater than 0 and displays it, only after the nullish coalescing operator has done its job to ensure user.id is neither null nor undefined.
FAQs Related to JavaScript’s Nullish Coalescing Operator
Can I use the nullish coalescing operator to handle empty strings?
The nullish coalescing operator does not consider an empty string as a nullish value. If you need to handle empty strings as well, you’ll want to use a different method or additional checks.
Is the nullish coalescing operator the same as ternary operator?
No, the nullish coalescing operator specifically checks for null or undefined values, while the ternary operator is a more general conditional operator.
How does nullish coalescing operator interact with default function parameters?
Default function parameters kick in when arguments are undefined. The nullish coalescing operator can be used inside a function to provide defaults for arguments that are either null or undefined.
Should I use the nullish coalescing operator for all default value assignments?
It’s ideal for cases where you truly only want to catch null or undefined. For broader falsy value checks, other methods like the logical OR might be more appropriate.
Advanced Techniques with Nullish Coalescing Operator
While the primary use of ?? is straightforward, it can also be a part of more advanced patterns and techniques in JavaScript.
Here’s an example that combines destructuring with ?? for default values:
const { age = 25 } = profile.data ?? {};
This construct not only provides a default object to destructure if profile.data is nullish but also sets a default age if it’s not explicitly provided.
Another technique involves chaining multiple nullish coalescing operators:
const preferredMode = user.settings.darkMode ?? system.settings.darkMode ?? 'light';
This code checks multiple possible sources for a ‘darkMode’ setting, using the first non-nullish value it finds, defaulting to ‘light’ mode if all else fails.
Interactive Configuration with Nullish Coalescing
Interactive configurations often rely on a mix of user inputs and default settings.
const interactiveConfig = { timeout: userInput.timeout ?? defaultConfig.timeout ?? 3000 };
In the example above, an application timeout value is being set based on user input, with a fallback to application’s defaults, and then to a hard-coded default.
Debugging Tips with Nullish Coalescing
If you suspect that nullish coalescing isn’t behaving as expected, console logging both sides of the ?? operator can provide insight.
console.log('User input:', userInput, 'Default:', 'Hello, guest!');
This simple debug line can reveal unexpected null or undefined values that might be influencing your logic.
Nullish Coalescing in Asynchronous Code
When dealing with asynchronous code, the ?? operator can help handle default values after awaiting promises.
async function getUserPreferences() {
const prefs = await fetchUserPreferences();
return prefs ?? getDefaultPreferences();
}
In this async function, preferences returned by fetchUserPreferences are used unless they’re nullish, in which case getDefaultPreferences is called.
Testing for Nullish Coalescing Compatibility
Given that ?? is a relatively new addition to JavaScript, testing for compatibility is wise.
If you’re working in an environment where you’re unsure about support:
if ('??' in window) { console.log('Nullish coalescing supported!'); }
While not foolproof, this can offer an initial check. For environments like Node.js, you might check the version, or use tools like Babel for transpiling.
Best Practices for Using Nullish Coalescing
Although ?? is a powerful tool, it’s important to use it judiciously.
One of the best practices is to avoid using ?? in conditions already guaranteed to be non-nullish, which could obscure the logic:
const nonNullishValue = someFunction(); console.log(nonNullishValue ?? 'default');
This is redundant and potentially confusing because nonNullishValue is, as the name implies, not expected to be nullish.
Refactoring Legacy Code with Nullish Coalescing
Refactoring existing code to use ?? can streamline default value assignments.
// Before
const setting = typeof someLegacySetting !== 'undefined' ? someLegacySetting : 'default';
// After
const setting = someLegacySetting ?? 'default';
This refactoring replaces a more verbose legacy check with a concise use of ??.
Integrating Nullish Coalescing in Modern JavaScript Projects
As JavaScript codebases grow and modernize, nullish coalescing should become a staple in your syntax vocabulary.
When introducing ?? to your team, consider pairing it with code comments for clarity:
const themeColor = user.preferences.color ?? /* default */ '#FFF';
This can help your team understand why nullish coalescing is used, especially if they are less familiar with the operator.
FAQs Related to JavaScript’s Nullish Coalescing Operator
How does the nullish coalescing operator help with object properties?
It allows you to provide default values for object properties that may not be initialized, preventing errors when trying to access them.
Can I use nullish coalescing for array elements?
Yes, it can be used to provide default values for potentially undefined array elements, similar to objects.
Do TypeScript and Babel support the nullish coalescing operator?
Yes, both TypeScript and Babel support ??, allowing you to use it even if the JavaScript environment does not natively support it.
Is there a way to refactor multiple OR (||) operator checks to nullish coalescing?
Yes, review each case and if only null or undefined should be replaced with a default, you can refactor to use ??, providing clearer intent and accuracy.
Can nullish coalescing be combined with optional chaining?
Absolutely. Combining nullish coalescing with optional chaining as obj?.property ?? 'default' is a powerful pattern for dealing with deep object structures safely.