SoftwareSideHustles
Debugging

How to Fix "TypeError: Cannot read properties of undefined" in JavaScript

What "Cannot read properties of undefined (reading 'x')" and its null twin actually mean, the six situations that cause it in browsers, React and Node.js, and how to fix the cause instead of hiding it.

By Software Side Hustles Editorial Team · Published · Updated · 5 min read

Quick answer: Cannot read properties of undefined (reading 'map') means the value to the left of .map is undefined. The bug is not in map — it is wherever that value was supposed to come from. Find which expression is undefined (the stack trace gives the line), then work out why: data not loaded yet, a misspelt property, a different API response shape, or a missing element. Optional chaining (?.) hides the symptom; fix the cause first.

What the error means

javascript
const user = undefined;
user.name;
// TypeError: Cannot read properties of undefined (reading 'name')

The message names the property you tried to read ('name'), not the variable that was undefined. In order.customer.address.city, an error "reading 'city'" means order.customer.address was undefined — the problem is one step to the left.

You will see the same bug phrased differently depending on the environment:

EnvironmentMessage
Chrome, Edge, Node.js (current)Cannot read properties of undefined (reading 'name')
Older Chrome / Node.jsCannot read property 'name' of undefined
Firefoxuser is undefined
Safariundefined is not an object (evaluating 'user.name')
Any, with nullCannot read properties of null (reading 'name')
Writing instead of readingCannot set properties of undefined (setting 'name')

Cause 1: data that has not loaded yet (React, Vue, async code)

The most common case in front-end code:

jsx
function Orders() {
const [orders, setOrders] = useState(); // initially undefined
useEffect(() => { fetchOrders().then(setOrders); }, []);
return <ul>{orders.map((o) => <li key={o.id}>{o.total}</li>)}</ul>;
// First render: Cannot read properties of undefined (reading 'map')
}

The component renders once before the fetch completes. Fix it by giving state the right empty value, and by rendering loading states deliberately:

jsx
const [orders, setOrders] = useState([]);
// or
if (!orders) return <p>Loading…</p>;

The same pattern appears in Node.js when you forget to await — the variable holds a Promise, and promise.data is undefined. See why your async function returns Promise pending.

Cause 2: the property name or path is wrong

javascript
const res = await fetch("/api/user").then((r) => r.json());
res.data.user.firstName; // API actually returns { user: { first_name: ... } }

Log the real shape before guessing: console.log(JSON.stringify(res, null, 2)). Common mismatches are snake_case versus camelCase, an extra data wrapper added by Axios (response.data), and arrays where you expected an object (res.users[0].name, not res.users.name).

Cause 3: an array index that does not exist

javascript
const first = items[0].name; // fails when items is []
const last = items[items.length].name; // off by one: should be length - 1

Arrays return undefined for missing indexes instead of throwing, so the error appears one step later. Check the length, or use items.at(-1) for the last element. See off-by-one and index out of range errors.

Cause 4: the DOM element was not found (the null version)

javascript
document.querySelector("#submit").addEventListener("click", send);
// TypeError: Cannot read properties of null (reading 'addEventListener')

querySelector returns null when nothing matches. Either the selector is wrong (#submit vs .submit, a typo), or the script ran before the HTML was parsed because it sits in <head> without defer. Use <script src="app.js" defer>, place scripts at the end of <body>, or wait for DOMContentLoaded.

Cause 5: this is undefined inside a callback

javascript
class Counter {
count = 0;
increment() { this.count++; }
}
const c = new Counter();
button.addEventListener("click", c.increment); // 'this' is the button, not c
setTimeout(c.increment, 100); // 'this' is undefined in strict mode

Passing a method as a callback detaches it from its object. Use an arrow function (() => c.increment()), c.increment.bind(c), or define the method as an arrow-function class field.

Cause 6: a function that does not return

javascript
function findUser(id) {
users.find((u) => u.id === id); // missing 'return'
}
findUser(1).name; // reading 'name' of undefined

Arrow functions with braces need an explicit return too: (x) => { x * 2 } returns undefined; (x) => x * 2 returns the value. Likewise Array.prototype.find returns undefined when nothing matches, so handle the not-found case.

How to debug it in under five minutes

  1. Read the stack trace — the top frame in your code gives the file and line. See how to read a stack trace.
  2. Identify the expression immediately left of the property in the message.
  3. Log or breakpoint just before that line and inspect the value and its parent object.
  4. Trace backwards to where the value is assigned: a fetch, a prop, a function return, a query.
  5. Fix the source, then decide whether the code should also handle the missing case.

Optional chaining: fix or cover-up?

javascript
const city = order?.customer?.address?.city ?? "Unknown";

Optional chaining is the right tool when a value is legitimately optional — a user without an address. It is the wrong tool when the value should exist and its absence is a bug: the error disappears, and so does the evidence, while the page silently shows "Unknown". Add ?. after you understand why the value was missing, not instead of understanding it.

TypeScript with strictNullChecks catches most of these at compile time by forcing you to handle undefined before property access.

Frequently asked questions

Why does the error say "reading 'map'" when map is not the problem?

The message reports the property being read. The value it was read from was undefined.

What is the difference between this error and "x is not defined"?

ReferenceError: x is not defined means no variable called x exists at all — usually a typo or a missing import. Cannot read properties of undefined means the variable exists but holds undefined.

How do I fix it in React when props are undefined?

Check the parent actually passes the prop with the same name, give the prop a default (function Card({ items = [] })), and handle loading states explicitly.

Where this skill pays off

Tracing an error back to its cause — and telling the difference between a real fix and ?. sprinkled over a bug — is what AI evaluation work pays developers to do when they judge a model's debugging answer. See what coding-focused AI data annotation involves.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy