TypeError: Cannot read properties of undefined
JavaScript tried to read a property from a value that is currently undefined.
What does this error mean?
An expression on the left side of a property access, such as `user.profile.name`, evaluated to `undefined` before JavaScript could read the next property.
Why does this happen?
- Data has not loaded yet.
- An array lookup returned no matching item.
- A function returned undefined unexpectedly.
- The property path does not match the response shape.
- A component rendered before required props were available.
AI explanation
JavaScript can only read a property from an object-like value. One step in the property chain produced `undefined`, so the next dot access had nowhere to look. Inspect the first missing value, not only the final property named in the message.
Quick fix
console.log({ valueBeforeFailure });
const name = user?.profile?.name ?? "Unknown";Step-by-step fix
Alternative solutions
Browser JavaScript
const result = value?.property ?? fallback;
Optional chaining is useful when absence is expected.
Node.js
if (!config.database) throw new Error("Missing database config");Fail early for required server configuration.
React
if (!user) return <Loading />;
Render a loading or empty state before accessing async data.
Real example
const user = users.find((item) => item.id === selectedId); console.log(user.name);
const user = users.find((item) => item.id === selectedId);
if (!user) {
console.warn("User not found", { selectedId });
return;
}
console.log(user.name);Frequently asked questions
Not always. It prevents the crash, but you should still verify whether the value is allowed to be missing. Required data should usually be validated earlier.