JS Nullish Coalescing Operator (??) Full Guide
Learn the JavaScript nullish coalescing operator (??) to provide default values only for null and undefined, avoiding common pitfalls of the || operator.
Setting default values in JavaScript has always been tricky. The logical OR operator (||) was the traditional tool for this, but it treats 0, "", and false as reasons to use the fallback. That causes real bugs when those are valid values. The nullish coalescing operator (??) fixes this by only falling back when the left side is null or undefined.
This guide covers the ?? operator in depth: how it works, why it replaced || for defaults, and the practical patterns that make your code more robust.
The Problem with || for Default Values
The || operator returns the right side whenever the left side is falsy. JavaScript has six falsy values: false, 0, "", null, undefined, and NaN. That makes || too aggressive for default values:
function createPlayer(name, score, active) {
return {
name: name || "Anonymous",
score: score || 100,
active: active || true
};
}
// Looks correct, but has bugs
const player = createPlayer("", 0, false);
console.log(player);
// { name: "Anonymous", score: 100, active: true }
// BUG: empty string, 0, and false were all valid inputs!The intent was to default only when values are actually missing (not provided). But || treats 0 as missing, "" as missing, and false as missing. These are legitimate values that got silently replaced.
How ?? Works
The nullish coalescing operator (??) returns the right side only when the left side is null or undefined. All other values, including 0, "", false, and NaN, pass through:
function createPlayer(name, score, active) {
return {
name: name ?? "Anonymous",
score: score ?? 100,
active: active ?? true
};
}
const player = createPlayer("", 0, false);
console.log(player);
// { name: "", score: 0, active: false }
// Correct! All valid inputs preservedHere is the complete truth table:
| Left Side Value | value || fallback | value ?? fallback |
|---|---|---|
null | fallback | fallback |
undefined | fallback | fallback |
0 | fallback | 0 |
"" (empty string) | fallback | "" |
false | fallback | false |
NaN | fallback | NaN |
"hello" | "hello" | "hello" |
42 | 42 | 42 |
Practical Use Cases
Configuration Objects with Valid Falsy Values
function applyConfig(userConfig) {
const config = {
volume: userConfig.volume ?? 75,
brightness: userConfig.brightness ?? 100,
muted: userConfig.muted ?? false,
username: userConfig.username ?? "Guest",
retryCount: userConfig.retryCount ?? 3
};
return config;
}
// User explicitly wants volume at 0 and muted true
const result = applyConfig({ volume: 0, muted: true, username: "" });
console.log(result);
// { volume: 0, brightness: 100, muted: true, username: "", retryCount: 3 }
// All user values preserved, only missing ones get defaultsFunction Parameter Defaults
While default parameters handle undefined, they do not trigger on null. The ?? operator handles both:
// Default params only trigger on undefined, NOT null
function greet(name = "World") {
console.log(`Hello, ${name}!`);
}
greet(null); // "Hello, null!" - default not triggered
// ?? handles both null and undefined
function greetBetter(name) {
const safeName = name ?? "World";
console.log(`Hello, ${safeName}!`);
}
greetBetter(null); // "Hello, World!"
greetBetter(undefined); // "Hello, World!"
greetBetter(""); // "Hello, !" - empty string preservedChaining Multiple Fallbacks
You can chain ?? to try multiple sources before settling on a final default:
const userTheme = null;
const savedTheme = undefined;
const systemTheme = "dark";
const defaultTheme = "light";
const theme = userTheme ?? savedTheme ?? systemTheme ?? defaultTheme;
console.log(theme); // "dark" (first non-nullish value)This reads like a priority list: try user preference first, then saved preference, then system setting, and finally the hardcoded default.
Combining ?? with Optional Chaining
The ?? operator pairs perfectly with optional chaining (?.) to safely access nested data and provide defaults in one expression:
const response = {
data: {
user: {
preferences: {
theme: "dark"
}
}
}
};
// Safe access + default in one line
const theme = response?.data?.user?.preferences?.theme ?? "light";
const lang = response?.data?.user?.preferences?.language ?? "en";
const fontSize = response?.data?.user?.preferences?.fontSize ?? 16;
console.log(theme); // "dark"
console.log(lang); // "en"
console.log(fontSize); // 16This combination has become the standard pattern for handling API responses in modern JavaScript.
?? Cannot Mix with && or || Without Parentheses
JavaScript throws a syntax error if you mix ?? with && or || without explicit parentheses. This is a deliberate design decision to prevent ambiguous expressions:
// SyntaxError - cannot mix without parentheses
// const result = a || b ?? c;
// const result = a && b ?? c;
// Correct - use parentheses to clarify intent
const result1 = (a || b) ?? c; // Apply || first, then ??
const result2 = a || (b ?? c); // Apply ?? first, then ||
const result3 = (a && b) ?? c; // Apply && first, then ??This rule exists because || and ?? have different semantics for falsy versus nullish values, and mixing them without parentheses would be confusing and error-prone.
Nullish Coalescing Assignment (??=)
The ??= operator assigns a value only if the current value is null or undefined. It is shorthand for if (x == null) x = value:
const options = {
color: null,
size: 0,
label: ""
};
options.color ??= "blue"; // null -> assigned "blue"
options.size ??= 10; // 0 -> NOT assigned (0 is not nullish)
options.label ??= "Default"; // "" -> NOT assigned ("" is not nullish)
options.icon ??= "star"; // undefined -> assigned "star"
console.log(options);
// { color: "blue", size: 0, label: "", icon: "star" }Compare with the OR assignment (||=):
| Operator | Assigns When Left Is | Leaves Alone |
|---|---|---|
??= | null or undefined | 0, "", false, NaN |
||= | Any falsy value | Truthy values only |
&&= | Any truthy value | Falsy values |
Real-World Example: Form Data Processor
Here is a practical example processing form submissions where empty strings and zeros are valid inputs:
function processFormData(formData) {
// Parse raw form values with safe defaults
const processed = {
firstName: formData.get("firstName") ?? "",
lastName: formData.get("lastName") ?? "",
age: parseInt(formData.get("age")) || null,
score: (() => {
const raw = formData.get("score");
const parsed = raw !== null ? Number(raw) : null;
return Number.isNaN(parsed) ? null : parsed ?? 0;
})(),
newsletter: formData.get("newsletter") ?? "off",
bio: formData.get("bio") ?? null
};
// Validate required fields
const errors = [];
if ((processed.firstName ?? "") === "") {
errors.push("First name is required");
}
if ((processed.lastName ?? "") === "") {
errors.push("Last name is required");
}
return { data: processed, errors, isValid: errors.length === 0 };
}This pattern ensures that empty string inputs from forms are preserved as empty strings rather than being replaced with defaults. The ?? operator correctly distinguishes between "the user typed nothing" (empty string, a valid value) and "the field was not present" (null).
Common Mistakes to Avoid
Using || When ?? Is Needed
// Bug: discount of 0% gets replaced with 10%
const discount = userDiscount || 10;
// Fix: only default when truly missing
const discount = userDiscount ?? 10;Assuming ?? Works Like a Ternary
const value = 0;
// ?? only checks null/undefined
const a = value ?? "fallback"; // 0 (not nullish)
// If you need to check for falsy, use || or a ternary
const b = value || "fallback"; // "fallback"
const c = value ? value : "fallback"; // "fallback"Forgetting to Use Parentheses with Mixed Operators
// Always wrap when mixing
const result = (config.debug || false) ?? defaultDebug;
// NOT: config.debug || false ?? defaultDebug (SyntaxError)|| vs ?? Decision Guide
| Situation | Use | Why |
|---|---|---|
| Numeric values (0 is valid) | ?? | 0 is not nullish |
| Boolean values (false is valid) | ?? | false is not nullish |
| String values (empty is valid) | ?? | "" is not nullish |
| Need to treat all falsy as "missing" | || | || catches all falsy |
| API response data with unknown shape | ?? | Only null/undefined are truly missing |
| Feature flags (on/off) | ?? | false means "explicitly off" |
Best Practices
- Default to
??over||for all new code that sets fallback values. It produces fewer bugs because it respects0,"", andfalseas valid data. - Combine with
?.for safe nested access:obj?.nested?.value ?? defaultis the gold standard for defensive data access. - Use
??=for lazy initialization of optional properties that should only be set once if missing. - Always add parentheses when mixing
??with||or&&to make the evaluation order explicit. - Document your choice when using
||instead of??. If you intentionally want falsy-fallback behavior, a comment explaining why prevents future developers from "fixing" it to??.
Rune AI
Key Insights
- Use
??instead of||for defaults: it preserves0,"",false, andNaNas valid values instead of replacing them - Pair with
?.for the safest data access:obj?.prop ?? fallbackis the modern standard for defensive coding ??=enables lazy initialization: assign default values only to properties that are actuallynullorundefined- Parentheses are mandatory with mixed operators: JavaScript throws a SyntaxError when
??is combined with||or&&without grouping - Choose
||deliberately, not by habit: when you need falsy-fallback behavior, document why to prevent accidental migration to??
Frequently Asked Questions
Can I use ?? with optional function parameters?
Does ?? short-circuit like || does?
What is the operator precedence of ???
Is ?? supported in TypeScript?
When should I still use || instead of ???
Conclusion
The nullish coalescing operator (??) is the correct tool for setting default values in JavaScript. Unlike the || operator, it only triggers on null and undefined, preserving valid values like 0, empty strings, and false. Combined with optional chaining (?.) and the assignment variant (??=), it forms a complete toolkit for safe, predictable data handling.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.