TypeError: Cannot read properties of undefined
Error message
Cannot read properties of undefined (reading 'x')
Quick summary
You used dot notation on a value that is `undefined` — the property doesn't exist because the object itself is missing.
Why this happens
The object was never assigned or was set to
undefinedA function returned
undefinedand the caller accessed a property on the resultAn array element or nested property is
undefined(e.g.,user.address.citywhenaddressis undefined)
Minimal example
let user;
console.log(user.name);let user;
console.log(user?.name);user is undefined, so accessing .name throws a TypeError — optional chaining (?.) returns undefined instead of throwing.
How to diagnose
Log the object right before the property access to confirm it is
undefinedTrace where the object should have been assigned or returned
Check API responses for missing fields that lead to
undefined
How to fix
Add a guard check before accessing the property (
if (obj))Use optional chaining (
obj?.property) to safely access nested propertiesProvide a default object so the property always exists
How to prevent
Use optional chaining (
?.) for all uncertain property accessesValidate API responses before using them
Related Resources
Related Lessons
- Objects
Learn how JavaScript objects work
Related Practice
- JavaScript Primitive Types
Check your understanding of primitive types including undefined.