Lingua-e
← Errors
JavaScript

Cannot read properties of undefined: What It Means and How to Fix It

Error reference

Cannot read properties of undefined

Language

JavaScript

Severity

High

When it happens

This error is thrown in JavaScript when you try to access a property on a value that is undefined.

Potential fixes

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.

Deep dive

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.

Potential fixes

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.

Examples

JavaScript

Code that triggers the error

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

Error output

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

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

Practice in English

How would you explain a Cannot read properties of undefined to a fellow dev? Choose the right phrase:

"I hit an error...

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