JavaScript
programmingjavascriptTroubleshootingBeginner
TypeError: Cannot read properties of undefined
Fix the most common JavaScript runtime error — accessing nested properties on undefined objects and asynchronous API responses.
Verified: 2026-09-30
Tested on:v8 current, node 22.x
Platforms:
webnode
#javascript#typescript#react#runtime#typeerror
Error Message
TypeError: Cannot read properties of undefined (reading 'name')
at renderProfile (user-profile.js:14:22)
at App (App.js:32:7)Symptoms
- Webpage crashes or shows a blank screen / white screen of death.
- Browser DevTools console prints red
Uncaught TypeError: Cannot read properties of undefined. - React component throws an error during initial render before an API fetch completes.
Why It Happens
In JavaScript, attempting to access property x on undefined (or null) using the dot accessor object.x or bracket accessor object['x'] throws an immediate TypeError.
Common causes:
- Asynchronous API fetching: Component attempts to read
user.profile.avatarbeforeuserhas loaded from the network. - Missing or optional nested object fields: Backend API response omits a nested object key.
- Array index out of bounds: Accessing
items[0].titlewhenitemsis an empty array[].
Quick Fix
Use Optional Chaining (?.):
// ✅ Safely returns undefined instead of throwing TypeError
const avatarUrl = user?.profile?.avatar;Step-by-Step Solutions
1. Optional Chaining with Nullish Coalescing (Recommended)
const userName = user?.profile?.name ?? "Anonymous";2. Guard Clauses in Functions
function formatAddress(user) {
if (!user || !user.address) {
return "No address provided";
}
return `${user.address.street}, ${user.address.city}`;
}3. Safe Destructuring with Defaults
const { name = "Guest", role = "Viewer" } = user || {};4. React State Initial Value
Always provide a realistic initial shape or render loading fallbacks:
function UserCard() {
const [user, setUser] = useState<User | null>(null);
if (!user) {
return <div className="animate-pulse">Loading profile...</div>;
}
return <div>Welcome, {user.name}!</div>;
}Prevention
- Enable strict mode in TypeScript (
"strict": trueintsconfig.json). - Use Zod or schema parsers on API responses to guarantee data shapes at runtime.
- Never assume external API responses will always include optional nested properties.
Developer Error Troubleshooting Library
Search exact error messages, understand root causes, and find verified copy-paste fixes for JavaScript, Node.js, React, Git, Docker, and Web protocols.
EADDRINUSE: address already in use
Complete troubleshooting guide for resolving port collisions and killing zombie processes on Linux, macOS, and Windows.