TypeError: Cannot read properties of undefined
TypeError: Cannot read properties of undefined in JavaScript means you read a property off something that does not exist. The crash is usually far from the real mistake — the value went missing earlier.
How do I fix TypeError: Cannot read properties of undefined?
To fix TypeError: Cannot read properties of undefined in JavaScript, locate the line causing the error and check the values right before it runs. Most occurrences happen because of array.find() found nothing. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does TypeError: Cannot read properties of undefined mean?
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.
Why does TypeError: Cannot read properties of undefined happen?
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.
Try it: fix this bug
easygetUserCity({}) throws TypeError: Cannot read properties of undefined (reading 'city').
function getUserCity(user) {
return user.address.city;
}More challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser — no install, no account needed.
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.