JavaScript: Optional Chaining and Nullish Coalescing
Introduced in ES2020, Optional Chaining (?.) and the Nullish Coalescing operator (??) solved two of the most annoying, boilerplate-heavy problems in JavaScript: navigating deeply nested objects safely and assigning default values without logic bugs.
1. Optional Chaining (?.)
The Problem
When working with JSON API responses, data structures are often deeply nested. If you try to access a property on undefined or null, JavaScript throws a fatal TypeError, crashing your app.
const user = { name: "Alice" };
// Crashes the app: TypeError: Cannot read properties of undefined (reading 'street')
console.log(user.address.street); Before ES2020, developers had to write tedious && checks:
const street = user && user.address && user.address.street;The Solution: ?.
Optional chaining stops evaluating and safely returns undefined if the value before the ?. is null or undefined.
const user = { name: "Alice" };
console.log(user?.address?.street); // undefined (No crash!)It also works beautifully with arrays and function calls:
// Array access
const firstItem = user?.hobbies?.[0];
// Function invocation
user?.getDetails?.(); 2. Nullish Coalescing Operator (??)
The Problem
Historically, developers used the Logical OR operator (||) to assign default fallback values.
const score = 0;
const finalScore = score || 100; // Expected 0, but got 100!Because || checks for falsy values, perfectly valid values like 0, "" (empty string), and false would accidentally trigger the fallback.
The Solution: ??
The Nullish Coalescing operator (??) strictly checks for nullish values: null or undefined. It ignores other falsy values.
const score = 0;
const text = "";
const missing = null;
console.log(score ?? 100); // 0 (0 is not null/undefined)
console.log(text ?? "N/A"); // "" (Empty string is not null/undefined)
console.log(missing ?? 404); // 404 (Triggers fallback because it IS null)3. The Ultimate Combo
These two operators are almost always used together. Optional chaining safely extracts a value that might be missing, and Nullish Coalescing provides a strict default if it actually is missing.
const user = {
settings: {
theme: "", // User explicitly wants no theme
volume: 0 // User explicitly muted the volume
}
};
// Without ?? (Buggy)
const theme = user?.settings?.theme || "dark"; // Incorrectly assigns "dark"
const vol = user?.settings?.volume || 50; // Incorrectly assigns 50
// With ?? (Correct)
const themeSafe = user?.settings?.theme ?? "dark"; // ""
const volSafe = user?.settings?.volume ?? 50; // 0Senior-Level Interview Answer
Optional chaining (
?.) provides a safe way to access deeply nested object properties, array indexes, or methods without having to manually validate that every preceding reference in the chain is non-null. If a reference evaluates to null or undefined, the expression short-circuits and returns undefined instead of throwing a TypeError.The Nullish Coalescing operator (
??) is a logical operator that returns its right-hand operand only when its left-hand operand is strictlynullorundefined. This heavily improves upon the legacy Logical OR (||) fallback pattern, which incorrectly overrides valid falsy values like0,false, and empty strings. Together,?.and??form the modern standard for extracting data and assigning robust default values.
Common Interview Mistakes
❌ Assuming ?. protects against undeclared variables
Optional chaining only works on properties of an object. It does not protect against variables that have never been declared.
console.log(someUndeclaredVariable?.name); // ReferenceError!❌ Using || when ?? is required
Interviewers frequently set up traps with configurations where timeout: 0 or enabled: false are passed in. If you use config.timeout || 3000, you will fail the test case because you just overrode the user's explicit 0 with 3000. Always use ?? for default values unless you explicitly want to filter out empty strings and zeros.
