BugHunt

TypeError: Cannot read properties of undefined

You read a property off something that does not exist. The crash is usually far from the real mistake — the value went missing earlier.

JavaScriptNull and undefined errors

What it means

Something you expected to be an object is undefined, and reading a property off undefined throws. The message names the property it tried to read, which tells you the shape you expected but not where the value disappeared. That gap is what makes it the most-reported error in JavaScript.

Common causes

1. Array.find() found nothing

find returns undefined when nothing matches. It does not throw and does not return an empty object.

Breaks

const price = items.find(i => i.id === id).price;

Works

const item = items.find(i => i.id === id);
const price = item ? item.price : 0;

2. Reading past the end of an array

JavaScript returns undefined for an out-of-range index rather than throwing, so the failure surfaces on the next line.

Breaks

for (let i = 0; i <= arr.length; i++) {
  console.log(arr[i].name);
}

Works

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i].name);
}

3. Optional chaining that only guards the first link

?. protects exactly the access it is attached to. The next dot is an ordinary access.

Breaks

const city = user?.address.city;

Works

const city = user?.address?.city;

4. Data has not arrived yet

State starts undefined and the first render reads it before the fetch resolves.

Breaks

return <p>{data.title}</p>;

Works

if (!data) return null;
return <p>{data.title}</p>;

How to find it in your own code

Work backwards from the crash to where the value was created, not where it exploded. The bug is at the creation. Log the whole object one line above the failure — it is usually undefined for an obvious reason once you see it.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors