JavaScript Nullish Coalescing Operator
Introduction
The nullish coalescing operator (??
) is a logical operator introduced in ECMAScript 2020 (ES11) that provides a more precise way to handle default values in JavaScript. This feature allows developers to provide fallback values specifically when dealing with null
or undefined
, without treating other falsy values (like 0
or empty strings) as missing values.
Before we dive into the nullish coalescing operator, let's understand why it was needed in the first place.
The Problem It Solves
Traditionally, JavaScript developers have used the logical OR operator (||
) to provide default values:
function greet(name) {
return "Hello, " + (name || "Guest");
}
console.log(greet("Alice")); // "Hello, Alice"
console.log(greet()); // "Hello, Guest"
But this approach has a significant limitation: the logical OR (||
) considers all falsy values (not just null
or undefined
) as triggers for the default value. Falsy values include:
false
0
""
(empty string)null
undefined
NaN
This can lead to unexpected behavior:
const count = 0;
const defaultCount = 10;
const result = count || defaultCount;
console.log(result); // 10, not 0 as you might expect!
Even though 0
might be a valid value for count
, the OR operator treats it as falsy and returns the default instead.
The Nullish Coalescing Operator to the Rescue
The nullish coalescing operator (??
) solves this problem by only returning the right-hand operand when the left-hand operand is specifically null
or undefined
(known as "nullish" values).
Basic Syntax
leftExpr ?? rightExpr
The result is:
- If
leftExpr
isnull
orundefined
, the expression returnsrightExpr
- Otherwise, the expression returns
leftExpr
Simple Examples
// Using nullish coalescing
const foo = null ?? 'default string';
console.log(foo); // "default string"
const baz = 0 ?? 42;
console.log(baz); // 0
const empty = "" ?? "default string";
console.log(empty); // "" (empty string is preserved)
Comparison with Logical OR
Let's compare the nullish coalescing operator (??
) with the logical OR operator (||
):
// Using nullish coalescing (??)
console.log(0 ?? "default"); // 0
console.log("" ?? "default"); // ""
console.log(false ?? "default"); // false
console.log(null ?? "default"); // "default"
console.log(undefined ?? "default"); // "default"
// Using logical OR (||)
console.log(0 || "default"); // "default"
console.log("" || "default"); // "default"
console.log(false || "default"); // "default"
console.log(null || "default"); // "default"
console.log(undefined || "default"); // "default"
Practical Examples
Default Function Parameters
function createUser(name, age, isAdmin) {
return {
name: name ?? 'Anonymous',
age: age ?? 18,
isAdmin: isAdmin ?? false
};
}
console.log(createUser('John', 25, true));
// { name: "John", age: 25, isAdmin: true }
console.log(createUser());
// { name: "Anonymous", age: 18, isAdmin: false }
console.log(createUser('Jane', 0, false));
// { name: "Jane", age: 0, isAdmin: false }
Notice how the age
parameter correctly preserves 0
as a valid value rather than defaulting to 18
.
Working with API Responses
When working with APIs, sometimes you'll receive data that might have nullish values:
// Simulating an API response
const apiResponse = {
user: {
name: 'Alice',
address: null
},
settings: undefined
};
// Safe access with nullish coalescing
const userAddress = apiResponse.user.address ?? 'No address provided';
const settings = apiResponse.settings ?? { theme: 'light', notifications: true };
console.log(userAddress); // "No address provided"
console.log(settings); // { theme: 'light', notifications: true }
Configuration Management
function initializeApp(config) {
const port = config.port ?? 3000;
const environment = config.environment ?? 'development';
const timeoutMs = config.timeoutMs ?? 5000;
console.log(`Starting app on port ${port} in ${environment} mode`);
console.log(`Timeout set to ${timeoutMs}ms`);
// More initialization code...
}
// This works even with potentially falsy values
initializeApp({
port: 0, // Special port 0 (let OS choose)
environment: "", // Empty string environment
timeoutMs: 500 // Lower timeout
});
// "Starting app on port 0 in mode"
// "Timeout set to 500ms"
Chaining the Nullish Coalescing Operator
You can chain multiple ??
operators to provide fallback options:
const firstName = null;
const lastName = null;
const nickName = "Shorty";
// Try firstName, then lastName, then nickName, and finally a default
const displayName = firstName ?? lastName ?? nickName ?? "Anonymous";
console.log(displayName); // "Shorty"
Short-circuiting
Like the logical operators &&
and ||
, the nullish coalescing operator exhibits short-circuit behavior - it only evaluates the right-hand side if the left-hand side is nullish:
function getDefaultValue() {
console.log("Generating default value...");
return "default";
}
const value = "existing" ?? getDefaultValue();
// getDefaultValue() is never called, so nothing is logged
const nullValue = null ?? getDefaultValue();
// Logs: "Generating default value..."
// nullValue = "default"
Combining with the Optional Chaining Operator
The nullish coalescing operator pairs particularly well with the optional chaining operator (?.
):
const user = {
profile: {
name: "Alex",
settings: null
}
};
const otherUser = {};
// Safe access + fallback value
const theme = user.profile?.settings?.theme ?? "light";
console.log(theme); // "light"
// Works even with deeply non-existent properties
const otherTheme = otherUser.profile?.settings?.theme ?? "dark";
console.log(otherTheme); // "dark"
Important Notes and Limitations
Cannot Combine Directly with && or ||
Due to JavaScript's grammar rules, you cannot directly combine ??
with &&
and ||
without parentheses:
// This will cause a syntax error
// const result = value1 && value2 ?? defaultValue;
// Instead, use parentheses to clarify precedence
const result = (value1 && value2) ?? defaultValue;
Nesting
You can nest nullish coalescing operations:
const result = value ?? (fallback1 ?? fallback2);
Browser Support
The nullish coalescing operator is supported in all modern browsers, but not in older browsers like Internet Explorer. If you need to support older browsers, you can use a transpiler like Babel to convert this syntax to equivalent code that works in older environments.
Summary
The nullish coalescing operator (??
) is a powerful addition to JavaScript that allows developers to provide fallback values specifically for null
and undefined
, without affecting other falsy values. This creates more predictable code, especially when working with values like 0
, empty strings, or false
that are valid in many contexts.
Key takeaways:
- Only treats
null
andundefined
as triggers for the fallback value - Works well with the optional chaining operator (
?.
) - Cannot be directly combined with logical operators without parentheses
- Provides short-circuit evaluation
Exercises
- Create a function that calculates a discount price, preserving a discount percentage of
0
as valid - Write a user profile manager that uses nullish coalescing to handle potentially missing data
- Refactor an existing piece of code that uses
||
for defaults to use??
instead and observe the differences - Build a configuration system that provides multilevel defaults using chained nullish coalescing
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)