Skip to content

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 undefined

  • A function returned undefined and the caller accessed a property on the result

  • An array element or nested property is undefined (e.g., user.address.city when address is undefined)

Minimal example

✗ Broken code
let user;
console.log(user.name);
✓ Fixed code
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 undefined

  • Trace 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 properties

  • Provide a default object so the property always exists

How to prevent

  • Use optional chaining (?.) for all uncertain property accesses

  • Validate API responses before using them

Related Resources

Related Glossary

Related Lessons

  • Objects

    Learn how JavaScript objects work

Related Practice

← Back to language