Safe Defaults
Nullish coalescing returns the right-hand value only when the left side is `null` or `undefined`.
This makes it perfect for defaults where 0, false, or empty strings are valid inputs.
JavaScript Tutorial
The nullish coalescing operator (??) provides safe defaults without overwriting valid falsy values like 0 or "".
It is perfect when data might be missing but falsy values still carry meaning.
Using `||` for defaults can accidentally replace legitimate values. That leads to subtle bugs in UI and data logic.
`??` solves this by defaulting only when the value is truly missing.
value ?? fallbackconst name = null;
const label = name ?? "Guest";
console.log(label); // "Guest"Nullish coalescing provides defaults only for null or undefined.
const count = 0;
console.log(count || 10); // 10
console.log(count ?? 10); // 0Use ?? to keep 0, false, and empty strings intact.
Nullish coalescing returns the right-hand value only when the left side is `null` or `undefined`.
This makes it perfect for defaults where 0, false, or empty strings are valid inputs.
Logical OR treats many values as falsy, including 0 and "". That can overwrite real data.
`??` only handles nullish values, so it is safer for numeric or boolean inputs.
Use `??` when you read from APIs or config files that may omit fields.
It keeps your code robust without hiding valid falsy values.
`?.` and `??` pair well: safely access deep data and provide a fallback in one expression.
This reduces verbose null checks and keeps code readable.
const response = { retries: 0 };
const retries = response.retries ?? 3;
console.log(retries); // 0Avoid overwriting meaningful falsy values from APIs.
const user = {};
const city = user.profile?.city ?? "Unknown";
console.log(city);Combine optional chaining with ?? for safe access and defaults.
Without
const count = 0;
const display = count || 10; // 10 (wrong for zero)With
const count = 0;
const display = count ?? 10; // 0 (correct)Switch to ?? for numeric or boolean defaults.
It only checks null and undefined.
Only apply defaults when a missing value is actually expected.
Wrap expressions to avoid precedence confusion.
Use ?? when 0, false, or "" are valid values that should be kept.
Only null and undefined.
Yes. `user?.name ?? "Guest"` is a common pattern.
Practice: Read a config value and default to 3000 only if it is null or undefined.
const config = { port: 0 };
// TODO: use ?? to keep 0 if provided
One Possible Solution
const config = { port: 0 };
const port = config.port ?? 3000;
console.log(port);It returns the right-hand value only when the left-hand value is null or undefined.
|| treats 0, false, and "" as false and will replace them. ?? will not.
Yes, but use parentheses because ?? has its own precedence rules.
Yes, it is supported in modern environments and can be transpiled for older ones.
Try the ?? examples and compare them with || to see the difference.