Skip to content

JavaScript Optional Chaining Error Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about JavaScript Optional Chaining Error Fix. We cover key concepts, practical examples, and best practices.

The Problem

Accessing deeply nested object properties in JavaScript throws TypeError: Cannot read properties of undefined when an intermediate property is null or undefined. Optional chaining (?.) short-circuits and returns undefined instead of throwing, but it must be used correctly.

Quick Fix

Step 1: Use ?. for nested property access

const user = {
    profile: null
};

// Wrong — throws TypeError
const city = user.profile.address.city;

// Right — optional chaining returns undefined
const city = user.profile?.address?.city;
console.log(city); // undefined

Step 2: Combine with nullish coalescing for defaults

const config = {
    database: null
};

// Wrong — OR operator treats empty string as falsy
const host = config.database?.host || 'localhost';

// Right — nullish coalescing only for null/undefined
const host = config.database?.host ?? 'localhost';
console.log(host); // localhost

Step 3: Call optional methods with ?.()

const math = {
    add: null
};

// Wrong — TypeError: math.add is not a function
const result = math.add(2, 3);

// Right — optional method call
const result = math.add?.(2, 3);
console.log(result); // undefined

Step 4: Access dynamic properties with ?.[]

const data = {
    items: null
};

// Wrong — TypeError
const first = data.items[0];

// Right — optional dynamic access
const first = data.items?.[0];
console.log(first); // undefined

Step 5: Chain multiple optional accesses

const response = await fetch('/api/user');
const data = await response.json();

// Safe deep access with defaults
const userName = data?.user?.name ?? 'Anonymous';
const userEmail = data?.user?.contact?.email ?? 'No email';

console.log(userName);  // depends on API response
console.log(userEmail); // depends on API response

Step 6: Optional chaining with logical operators

function getDisplayName(user) {
    // Wrong — throws on null user
    return user.profile.displayName;

    // Right — safe with defaults
    return user?.profile?.displayName ?? user?.username ?? 'Guest';
}

const user1 = null;
const user2 = { username: 'alice' };
const user3 = { profile: { displayName: 'Alice' } };

console.log(getDisplayName(user1)); // Guest
console.log(getDisplayName(user2)); // alice
console.log(getDisplayName(user3)); // Alice

Prevention

  • Use optional chaining for any property access where the parent may be nullish
  • Combine ?. with ?? to provide meaningful defaults
  • Do not overuse optional chaining — use it only when null/undefined is expected
  • Validate API response schemas early to avoid deep optional chains
  • Use TypeScript with strict null checks for compile-time safety

Common Mistakes with optional chaining

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' causing stack overflow on large lists

These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Does optional chaining work on the left side of assignment?

No. Optional chaining is read-only. obj?.prop = value throws SyntaxError. Check for nullish explicitly: if (obj) obj.prop = value.

What is the difference between ?. and && for optional access?

?. checks specifically for null or undefined (nullish). && checks for any falsy value (null, undefined, 0, '', false). Use ?. when you only want to guard against missing objects, not falsy values.

Can I use optional chaining with array index access?

Yes. Use arr?.[index] to safely access an array element when the array may be null or undefined. Returns undefined if the array is nullish.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro