Optional Chaining and Nullish Coalescing
Optional chaining (?.) and nullish coalescing (??) are two powerful ES2020 features that simplify dealing with null and undefined values. They make your code safer, more concise, and easier to read—especially in React when handling props, API responses, or deeply nested data.
Optional chaining allows you to access properties deeply without explicitly checking if each intermediate reference is null or undefined. If any part is null or undefined, the expression short‑circuits and returns undefined.
Basic Syntax
const user = {
name: 'Alice',
address: {
city: 'New York'
}
};
// Without optional chaining – verbose and error‑prone
const city = user && user.address && user.address.city;
// With optional chaining – clean and safe
const city = user?.address?.city;
console.log(city); // 'New York'
// If a property is missing
const country = user?.address?.country;
console.log(country); // undefined (no error!)
Optional Chaining with Function Calls
const obj = {
greet: () => 'Hello'
};
const result = obj.greet?.(); // returns 'Hello'
const missing = obj.bye?.(); // returns undefined (no error)
Optional Chaining with Bracket Notation
const key = 'city';
const city = user?.address?.[key];
console.log(city); // 'New York'
Note: Optional chaining is short‑circuiting – if the left side is null or undefined, the right side is not evaluated.
React Use Case – Safe Props Access
function UserProfile({ user }) {
// Safe access even if user or user.address is undefined
const city = user?.address?.city ?? 'Unknown';
return <div>City: {city}</div>;
}
The nullish coalescing operator ?? returns the right‑hand side only when the left‑hand side is null or undefined. Unlike || (logical OR), it does not treat other falsy values (0, '', false, NaN) as missing.
Basic Example
const value = null ?? 'default'; // 'default'
const value2 = undefined ?? 'fallback'; // 'fallback'
const value3 = 0 ?? 42; // 0 (because 0 is not null or undefined)
const value4 = '' ?? 'text'; // '' (empty string is not null or undefined)
const value5 = false ?? true; // false
Combining with Optional Chaining
const user = { name: 'Bob' };
const displayName = user?.name ?? 'Guest'; // 'Bob'
const displayAge = user?.age ?? 18; // 18 (since age is undefined)
Important: ?? only checks for null and undefined. Use it when you want to provide a default only when a value is truly missing, not just falsy.
React Use Case – Default Values for Props
function PriceDisplay({ price }) {
// If price is 0, we want to display 0, not a default
const displayPrice = price ?? 'N/A';
return <div>Price: {displayPrice}</div>;
}
// If price is 0, it shows 0; if price is null/undefined, shows 'N/A'
| Operator | Falsy values treated as missing | Use case |
|---|---|---|
|| |
0, '', false, null, undefined, NaN |
When any falsy should trigger the fallback |
?? |
only null and undefined |
When you only want to fall back for missing values |
const count = 0;
const result1 = count || 10; // 10 (because 0 is falsy)
const result2 = count ?? 10; // 0 (because 0 is not null/undefined)
const name = '';
const display1 = name || 'Anonymous'; // 'Anonymous'
const display2 = name ?? 'Anonymous'; // '' (empty string is not null/undefined)
Best Practice: Use ?? when you want to distinguish between a legitimate falsy value (like 0 or '') and a truly missing value. Use || when you want any falsy value to trigger a default.
Safe API Data Access
function ProductDetails({ product }) {
const name = product?.name ?? 'Unnamed Product';
const price = product?.price ?? 0;
const category = product?.category?.name ?? 'General';
const tags = product?.tags ?? [];
return (
<div>
<h2>{name}</h2>
<p>${price}</p>
<p>Category: {category}</p>
<ul>
{tags.map((tag, i) => <li key={i}>{tag}</li>)}
</ul>
</div>
);
}
Form Handling with Defaults
function SettingsForm({ settings }) {
const [theme, setTheme] = useState(settings?.theme ?? 'light');
const [notifications, setNotifications] = useState(settings?.notifications ?? true);
// ...
}
Chaining with Optional Method Calls
function EventHandler({ onClick }) {
const handleClick = () => {
onClick?.(); // safely call if provided
};
return <button onClick={handleClick}>Click</button>;
}
- Optional chaining (
?.) – safely access nested properties; short‑circuits if a reference isnullorundefined. - Nullish coalescing (
??) – provides a default only when the left side isnullorundefined. - Use
??over||when you need to preserve valid falsy values like0,'', orfalse. - Both are widely used in React for safer prop handling, default values, and cleaner code.
Key Takeaway
"Optional chaining and nullish coalescing make your code safer and more expressive—use them to avoid tedious null checks and to distinguish missing values from falsy ones."
Happy coding!