In JavaScript, accessing nested object properties or handling default values can lead to errors or unexpected results if the data is missing or null/ undefined. Two modern operators—Optional Chaining (?.) and Nullish Coalescing (??)—help write safer and cleaner code.

💡 Optional Chaining (?.)
Safely access deeply nested properties without throwing errors if an intermediate property is null or undefined.
Example:
📌 Deep Dive: Optional Chaining
const user = { profile: { name: 'Alice' } };
// Without optional chaining - throws if profile doesn't exist
// const userName = user.profile.name; // Error if profile is undefined
// With optional chaining
const userName = user.profile?.name;
console.log(userName); // "Alice"
// If profile is undefined
const user2 = {};
const user2Name = user2.profile?.name;
console.log(user2Name); // undefined (no error)
Optional chaining also works with:
- Function calls:
func?.() - Array elements:
arr?.[index]
💡 Nullish Coalescing Operator (??)
Returns the right-hand value only if the left-hand value is null or undefined. Useful for setting default values without overriding falsy but valid values like 0 or ''.
📌 Deep Dive: Nullish Coalescing
const inputValue = 0;
// Using || (logical OR) treats 0 as falsy, so default used
const orResult = inputValue || 42;
console.log(orResult); // 42 (unexpected for 0)
// Using ?? (nullish coalescing) only replaces null or undefined
const nullishResult = inputValue ?? 42;
console.log(nullishResult); // 0 (correct)
| Operator | Behavior |
|---|---|
|| | Returns right operand if left is falsy (0, '', false, null, undefined) |
?? | Returns right operand only if left is null or undefined. Preserves 0, '', false |
⚠️ Important Usage Note
Do not combine || and ?? without parentheses due to operator precedence differences which can cause unexpected results.
Together, these two operators simplify safe property access and default value assignment, making your code more robust and easier to read.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What will obj?.prop return if obj is null?
Question 2 of 2
What is the result of '' ?? 'default'?
Loading results...