javascriptseverity: critical
TypeError: Cannot read properties of undefined

JavaScript TypeError: Cannot read properties of undefined (or null)

TypeError: Cannot read properties of undefined/null

95% fixable~10 mindifficulty: beginner

Verified against MDN Web Docs — TypeError, ECMAScript 2022 spec §13.5.3, V8 engine error messages · Updated June 2026

> quick_fix

Use optional chaining (?.) to safely access nested properties: `user?.address?.city` returns undefined instead of throwing when any part is null or undefined.

// BROKEN: throws if user or user.address is undefined
const city = user.address.city;

// FIXED: optional chaining — returns undefined instead of throwing
const city = user?.address?.city;

// With nullish coalescing fallback
const city = user?.address?.city ?? 'Unknown';

// For array access
const first = arr?.[0]?.name;

// For function calls
const result = obj?.method?.();

// Check before async operations
async function loadUser(id) {
    const user = await fetchUser(id);
    if (!user) throw new Error(`User ${id} not found`);
    return user.profile.name; // safe now
}

What causes this error

TypeError: Cannot read properties of undefined (reading 'x') is thrown when you try to access a property on a value that is undefined or null. Common causes: accessing a deeply-nested property before checking if intermediate objects exist, accessing an array element that doesn't exist, calling a method on the result of an async operation before it resolves, or accessing a DOM element that doesn't exist in the document.

> advertisementAdSense placeholder

How to fix it

  1. 01

    step 1

    Read the error — it tells you which property was accessed and what value it was on

    The message 'Cannot read properties of undefined (reading \"city\")' tells you: city was the property being read, and the object it was read from was undefined. Identify the chain of property accesses on that line and find which one is undefined.

  2. 02

    step 2

    Use optional chaining (?.) for nested access

    Replace `a.b.c` with `a?.b?.c`. Optional chaining short-circuits and returns undefined if any intermediate value is null or undefined. Available in all modern browsers and Node.js 14+.

  3. 03

    step 3

    Add a null/undefined check at the source

    Optional chaining suppresses the error but does not fix the root cause. Trace back: why is the object undefined? Is it: an async operation that hasn't resolved yet, an API response that returned no data, a DOM query that found no element? Fix the data problem, not just the access.

  4. 04

    step 4

    Handle async data correctly

    A common React/Vue source: accessing `data.user.name` before `data` has loaded. Solution: guard with conditional rendering: `{data && <p>{data.user.name}</p>}` or in JavaScript: `if (data?.user) { ... }`. Never access API response properties before the await completes.

  5. 05

    step 5

    Provide default values with nullish coalescing (??)

    Combine with ??: `const name = user?.profile?.name ?? 'Anonymous'`. This provides 'Anonymous' if any part of the chain is null/undefined, or if the name property itself is null/undefined.

How to verify the fix

  • Reproduce the scenario that caused the error — no TypeError should appear
  • Test the null/undefined case explicitly: pass null or undefined and verify graceful handling
  • Open the browser console — zero TypeError messages on the affected page

Why TypeError: Cannot read properties of undefined happens at the runtime level

In JavaScript, accessing a property on null or undefined triggers a TypeError because the [[Get]] internal operation is only defined for objects. When the engine encounters `undefined.city`, it attempts to perform [[Get]](undefined, 'city') which the spec defines as throwing a TypeError. Prior to optional chaining (ES2020), every nested property access required explicit null-checking, making defensive code verbose. Optional chaining (?.) was added to the spec specifically to address the frequency and verbosity of this null-check pattern.

Common debug mistakes for TypeError: Cannot read properties of undefined

  • Accessing nested API response properties before the async fetch has completed
  • Calling document.getElementById() and accessing properties without checking if the element exists
  • Using array[0].property without checking if the array has any elements
  • Destructuring `const { name } = user` without checking if `user` is defined

When TypeError: Cannot read properties of undefined signals a deeper problem

TypeError: Cannot read properties is the JavaScript equivalent of NullPointerException, and it is the most common runtime error in JS because the language has no null safety in its type system. The optional chaining operator (?.) is the tactical fix, but the strategic fix is TypeScript with strict null checks enabled — the compiler then enforces at build time that nullable values are checked before property access. For React applications, a data-loading state machine (loading/error/success states) prevents the class of async-data TypeErrors entirely.

Editor's take

TypeError: Cannot read properties of undefined/null is the most common JavaScript runtime error — browser telemetry from Sentry and similar services consistently ranks it as the number one exception across millions of web applications. It means you accessed a property or called a method on a value that is `undefined` or `null`. The modern fix is optional chaining (`obj?.prop?.nested`), which short-circuits to `undefined` instead of throwing. But blindly adding `?.` everywhere is the wrong approach — it silences the error without fixing the root cause, and you end up rendering empty UIs instead of useful error messages. In React applications, this error most often appears when component props are undefined because data hasn't loaded yet — the component renders before the API response arrives. The proper fix is conditional rendering or a loading state, not optional chaining on every prop access. In async code, this error frequently signals a timing issue: you're accessing a response object before the `await` completes, or a callback fires after the component unmounts and the ref is null. In production monitoring, the key diagnostic is the property name in the error message — 'Cannot read properties of undefined (reading "map")' tells you that the array you expected to iterate over is undefined. That single property name usually points you directly to the bug. TypeScript with strict null checks eliminates this entire error class at compile time.

By Bikram Nath · Curator · Updated June 2026

Frequently asked questions

What is the difference between null and undefined in JavaScript?

undefined means a variable has been declared but not assigned a value, or a property does not exist on an object. null is an explicit assignment meaning 'no value'. Both cause TypeError when you try to read properties from them. Optional chaining (?.) handles both: `null?.prop` and `undefined?.prop` both return undefined without throwing.

Why does this error happen more in React/Vue than in regular JavaScript?

UI frameworks render components before async data loads. If you access `props.user.name` synchronously and the user data is fetched asynchronously, the component renders before the data arrives — and user is undefined at that first render. The fix is to conditionally render only when data is available.

Does optional chaining work in all browsers?

Optional chaining (?.) is supported in all modern browsers (Chrome 80+, Firefox 74+, Safari 13.1+, Edge 80+) and Node.js 14+. Babel and TypeScript compile it down for older targets. IE11 does not support it natively.

disclosure:Errordex runs AdSense, has zero third-party affiliate or sponsored links, and occasionally links to the editor’s own paid digital products (clearly labelled). Every fix is cross-referenced against the official sources listed in the “sources” sidebar before it ships. If a fix here didn’t work for you, please email so we can update the page.