Fix: Cannot read property of undefined
The #1 JavaScript runtime error. Here's the 30-second fix, why it happens, and how to prevent it.
Last updated: October 2026
Use optional chaining. Add ?. before every property access that might be undefined:
// ❌ Throws if user or user.profile is undefined
const city = user.profile.address.city;
// ✅ Returns undefined safely
const city = user?.profile?.address?.city;
// ✅ With a default fallback
const city = user?.profile?.address?.city ?? "Unknown";
What the error means
You tried to read a property (like .name or .map()) on a variable that is undefined or null. JavaScript can't read properties of nothing, so it throws.
// This fails
const user = undefined;
console.log(user.name); // ❌ TypeError
// Because JavaScript does this internally:
// undefined.name → TypeError
Why it happens (root causes)
There are three real causes, in order of frequency:
Async data hasn't loaded yet
The component renders before the fetch completes. On the first render, the value is undefined.
function UserCard() {
const [user, setUser] = useState();
useEffect(() => {
fetchUser().then(setUser);
}, []);
return <div>{user.name}</div>; // ❌ Fails on first render
}
Typo or wrong variable name
The variable exists but you're reading from a different one, or the property name is misspelled.
const userData = { name: "Alice" };
console.log(user.data); // ❌ user is undefined
console.log(userData.name); // ✅
Function returned nothing
The function was supposed to return an object, but a code path returns undefined.
function getUser(id) {
if (id === 1) return { name: "Alice" };
// ❌ Forgot return for other IDs
}
const user = getUser(2);
console.log(user.name); // ❌ user is undefined
Three ways to fix it
Optional chaining (best for optional data)
Stops at the first undefined value and returns undefined instead of throwing.
// Chain the access
const city = user?.profile?.address?.city;
// Works with function calls too
const length = user?.friends?.length;
// Works with array access
const first = user?.friends?.[0];
Nullish coalescing (best for defaults)
Combine with ?? to provide a fallback when the value is null or undefined.
const name = user?.name ?? "Guest";
const items = data?.items ?? [];
const count = response?.count ?? 0;
// Now items.map() and count + 1 work safely
items.map(item => renderItem(item));
Guard clauses (best for required data)
When the value should exist, fail loudly rather than silently returning undefined.
function renderUser(user) {
if (!user) {
return null; // or throw, or show a fallback
}
return <div>{user.name}</div>;
}
// Or with early return
function renderUser(user) {
if (!user) return null;
return <div>{user.name}</div>;
}
🛡️ How to prevent it
- Initialize state with defaults. Use
useState({})oruseState([])instead ofuseState(). - Use TypeScript. The compiler catches
possibly undefinedaccess at build time. - Validate API responses. Use Zod or io-ts to ensure the shape before using it.
- Prefer
??over||.||treats 0 and "" as falsy —??doesn't. - Name your variables clearly. Most "undefined" bugs are actually typos.
- Log before you access. When debugging,
console.log(user)first — 90% of the time you'll spot the issue instantly.
Common variations of this error
| Error message | Same fix? |
|---|---|
| Cannot read properties of undefined | ✅ Yes |
| Cannot read properties of null | ✅ Yes |
| Cannot read property 'x' of undefined | ✅ Older wording |
| undefined is not an object | ✅ Safari wording |
| 'x' is undefined | ⚠️ Different error — variable not declared |
❓ Frequently asked questions
How do I fix Cannot read property of undefined in JavaScript?
The fastest fix is optional chaining: obj?.prop?.nested. If you need a fallback value, use nullish coalescing: obj?.prop ?? 'default'. For nested access in loops, check the parent exists before iterating.
What is the difference between Cannot read property of undefined and Cannot read properties of null?
undefined means the variable was declared but never assigned a value. null means it was explicitly set to nothing. Both throw the same error type and both are fixed the same way.
Why does my data work sometimes and throw this error other times?
This usually means the data arrives asynchronously. On first render the value is undefined, then it loads. Guard the access with optional chaining or conditional rendering until the data arrives.
Is optional chaining supported in all browsers?
Yes. Optional chaining (?.) has been Baseline since 2020 and works in every modern browser including Chrome, Firefox, Safari, and Edge. It also works in Node.js 14 and later.
Can I use try/catch instead of optional chaining?
Yes but it's worse. try/catch hides the actual problem and makes debugging harder. Optional chaining documents that the value might be missing, which is more honest and readable code.