Optional Chaining & Nullish Coalescing

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.

Illustration of optional_chaining_nullish_coalescing
Illustration of optional_chaining_nullish_coalescing

💡 Optional Chaining (?.)

Safely access deeply nested properties without throwing errors if an intermediate property is null or undefined.

Example:

📌 Deep Dive: Optional Chaining

JAVASCRIPT
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

JAVASCRIPT
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)
Comparison: Logical OR (||) vs Nullish Coalescing (??)
OperatorBehavior
||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.