Lingua-e
JavaScript

What is a Cannot read properties of undefined?

← Errors

This error is thrown in JavaScript when you try to access a property on a value that is undefined. undefined has no properties, so any property access on it immediately throws a TypeError. It is one of the most frequent runtime errors in JavaScript codebases.

Why it happens

  • A function returns undefined (implicitly or explicitly) and the caller accesses a property on the return value without checking.
  • An array index that is out of bounds returns undefined, and then a property is accessed on it.
  • An API response or async operation has not resolved yet and the variable is still undefined.
  • A destructured variable that was not present in the source object defaults to undefined.

Examples

JavaScript

Code that triggers the error

const user = undefined;
console.log(user.name);

Error output

TypeError: Cannot read properties of undefined (reading 'name')

How to fix it

Use optional chaining (?.) to safely access nested properties without throwing. Add null or undefined checks before accessing properties when you cannot guarantee a value exists. Enable TypeScript strict mode to catch these issues at compile time.

Fixed code

const user = undefined;

// Option 1: guard with a check
if (user !== undefined && user !== null) {
  console.log(user.name);
}

// Option 2: optional chaining
console.log(user?.name);  // undefined, no error

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free