Skip to content

How to Fix TypeError: Cannot read property of undefined in JavaScript

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix TypeError: Cannot read property of undefined in JavaScript. We cover key concepts, practical examples, and best practices.

The Problem

JavaScript throws TypeError: Cannot read properties of undefined (reading 'X') when you try to access a property on undefined or null, typically from an API response missing a nested field or an uninitialized variable.

Quick Fix

Step 1: Locate the undefined value

The error message tells you which property was being accessed. Log the parent object to inspect it:

const user = { name: 'Alice' };
console.log(user.address.city);
TypeError: Cannot read properties of undefined (reading 'city')

Inspect each level of the object:

const user = { name: 'Alice' };
console.log('user:', user);
console.log('user.address:', user.address);
user: { name: 'Alice' }
user.address: undefined

Step 2: Use optional chaining (?.)

Optional chaining returns undefined instead of throwing:

const user = { name: 'Alice' };
console.log(user?.address?.city);
undefined

Step 3: Provide default values with nullish coalescing (??)

Combine optional chaining with a fallback:

const user = { name: 'Alice' };
const city = user?.address?.city ?? 'Unknown';
console.log(city);
Unknown

Step 4: Guard with an if check

For older environments, use explicit conditionals:

const user = { name: 'Alice' };
let city = 'Unknown';
if (user && user.address) {
    city = user.address.city;
}
console.log(city);
Unknown

Prevention

  • Use optional chaining (?.) for every nested property access.
  • Validate API responses with if (response.data) before accessing fields.
  • Initialize objects with defaults: const config = { theme: { color: 'blue' } }.
  • Use TypeScript or JSDoc to catch missing properties at compile time.
  • Normalize API responses at the network boundary with default values for every field.

Common Mistakes with typeerror undefined

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

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

### Why does JavaScript throw "Cannot read property of undefined" instead of returning undefined?

JavaScript throws a TypeError because accessing a property on undefined is a language-level violation. The language designers chose to throw rather than silently return undefined so developers catch bugs early. Optional chaining (?.) was introduced in ES2020 as a safe alternative that returns undefined without throwing.

What is the difference between optional chaining and the logical AND operator?

Optional chaining (?.) short-circuits and returns undefined if the left side is null or undefined. The AND operator (&&) checks truthiness, which means it also stops on falsy values like 0, '', or false. Use ?. when you specifically want to guard against null/undefined. Use && when you need to guard against all falsy values.

Can I use optional chaining in older browsers?

Optional chaining works in all modern browsers (Chrome 80+, Firefox 74+, Safari 13.1+). For older browsers like Internet Explorer, you need a Babel transform. Alternatively, use lodash _.get() or explicit if checks as a polyfill strategy.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro