Optional Chaining and Nullish Coalescing
6 min read
Optional Chaining (?.)
Optional chaining lets you safely read deeply nested properties without manually checking every intermediate value. If any step is null or undefined, the whole expression short-circuits to undefined instead of throwing.
javascript
const user = {
name: "Alice",
address: {
city: "Paris"
}
};
// Without optional chaining:
const zip1 = user && user.address && user.address.zip;
// With optional chaining:
const zip2 = user?.address?.zip; // undefined (no throw)
const len = user?.name?.length; // 5
// Also works with method calls and bracket notation
const tag = document.querySelector(".hero")?.tagName;
const val = config?.["debug"];Nullish Coalescing (??)
?? returns the right-hand operand only when the left is null or undefined. Unlike ||, it does not treat 0, "", or false as missing.
javascript
const config = { timeout: 0, retries: null };
const timeout = config.timeout ?? 3000; // 0 (not 3000!)
const retries = config.retries ?? 3; // 3
const logLevel = config.logLevel ?? "info"; // "info"Combine both: user?.profile?.bio ?? "No bio yet" — safe traversal with a fallback. This pattern appears constantly in real-world React and Next.js code.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises