JavaScript TypeError — Cannot Read Properties of Undefined
Fix the most common JavaScript error: TypeError. Covers null/undefined access, optional chaining, type guards, and debugging techniques for frontend and Node.js.
Detailed Explanation
JavaScript TypeError
TypeError is the most common runtime error in JavaScript. The most frequent variant is Cannot read properties of undefined (reading 'x') or Cannot read properties of null (reading 'x').
Most Common Variants
// Cannot read properties of undefined
const user = {};
console.log(user.address.city); // TypeError!
// x is not a function
const x = 42;
x(); // TypeError: x is not a function
// Cannot set properties of undefined
const obj = {};
obj.nested.value = 1; // TypeError!
Modern Solutions
1. Optional chaining (?.):
// Safe property access
const city = user?.address?.city; // undefined instead of TypeError
// Safe method calls
const result = api?.getData?.();
// Safe array access
const first = items?.[0]?.name;
2. Nullish coalescing (??):
// Default value for null/undefined
const name = user?.name ?? "Anonymous";
const port = config?.port ?? 3000;
3. Destructuring with defaults:
const { name = "Unknown", age = 0 } = user || {};
Common Scenarios in React
// Bad: accessing state before it's loaded
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);
// TypeError on first render: user is null
return <h1>{user.name}</h1>;
// Fix: guard against null
return <h1>{user?.name ?? "Loading..."}</h1>;
}
TypeScript Prevention
// TypeScript catches many TypeErrors at compile time
interface User {
name: string;
address?: {
city: string;
};
}
function getCity(user: User): string {
// TypeScript error: Object is possibly 'undefined'
return user.address.city;
// Fix: optional chaining
return user.address?.city ?? "Unknown";
}
Debugging Tips
- Check the stack trace — it tells you the exact line
- Add console.log before the failing line to inspect values
- Use browser DevTools breakpoints
- Check for async timing issues (data not loaded yet)
- Verify API response shape matches your assumptions
Use Case
TypeError accounts for over 50% of JavaScript runtime errors according to error tracking services. It is especially prevalent in React applications where state can be null during initial render, in API integrations where response shapes vary, and in deeply nested object access. Mastering optional chaining and null guards is essential for writing crash-free JavaScript.