---
title: "TypeError: Cannot read properties of undefined"
description: "In JavaScript, encountering errors is a natural part of development. One frequent runtime error is TypeError: Cannot read properties of undefined. This…"
url: https://www.danny.engineering/answer/javascript/typeerror-cannot-read-properties-of-undefined
author: Danny
published: 2025-02-04T00:00:00.000Z
updated: 2025-02-04T19:40:00.000Z
tags: ["Javascript"]
---

# TypeError: Cannot read properties of undefined

In JavaScript, encountering errors is a natural part of development. One frequent runtime error is `TypeError: Cannot read properties of undefined`. This typically occurs when your code attempts to access, invoke, or operate on a property or method of a variable that hasn’t been properly initialised or is undefined. Understanding why this happens – and how to resolve it – is crucial for debugging and writing resilient code.

## Problem

The error `TypeError: Cannot read properties of undefined` arises when your program attempts to access a property or method on a variable or object that is `undefined`. This is a common occurrence, especially in dynamic and loosely typed languages like JavaScript.

```javascript
let person;
console.log(person.name); // TypeError: Cannot read properties of undefined
```



Here, the variable `person` is declared but has no value assigned, leaving it `undefined`. Attempting to access `name` results in a `TypeError`, since there is no property to read from an undefined value.

### Common Causes
1. A variable is unintentionally `undefined` or `null`.
2. The object’s expected structure is incomplete or misaligned.
3. Data from external sources (e.g., API responses) doesn’t match your assumptions.
4. Improper chaining of object properties without safeguards.

Understanding the root cause is key to fixing this issue effectively.

## Solution

Below are two approaches to handle this error, depending on the context in which it occurs.

### Validate the Variable or Object Before Accessing Properties

Always check if the variable or object is defined before attempting to access its properties. Use a conditional statement (e.g., `if`) or the optional chaining (`?.`) operator.

```javascript
let person;

// Using a conditional check
if (person) {
  console.log(person.name); // Won’t trigger an error
} else {
  console.log("person is undefined or null.");
}

// Using optional chaining
console.log(person?.name); // Safely returns undefined without throwing an error
```

- The `if` statement checks whether `person` is a truthy value (i.e., not `null` or `undefined`) before accessing its properties.
- Optional chaining (`?.`) ensures safe navigation, returning `undefined` if `person` is invalid.

- Using optional chaining prevents errors but can also obscure structural issues in your data. Always ensure your data schema is sound.

### Provide Default Values Using Nullish Coalescing or Defaults

When you expect a variable might be undefined, assign a default value to ensure the code runs as intended.

```javascript
let person;

// Nullish coalescing (??)
let personName = person?.name ?? "Default Name";
console.log(personName); // "Default Name"

// Default object structure
person = person || { name: "Default Name" };
console.log(person.name); // "Default Name"
```
- The `??` operator assigns a fallback value if the left-hand side is `null` or `undefined`.
- Using the `||` operator, the whole object is defaulted if `person` is falsey.

However be cautious as overusing fallback values can hide underlying bugs in your code logic. Use them sparingly and document intentions.

## Further Considerations

### Performance Implications
- Excessive safety checks, especially in critical paths, may inadvertently introduce overhead. Only validate or default variables where necessary.
- Prefer safe data-handling patterns over workarounds to preserve code quality and maintainability.

### Security Concerns
- If the error stems from untrusted external data (e.g., API responses), consider sanitising the data properly before attempting access. Never assume the shape or validity of external inputs.

### Real-World Applications
- This error often appears in web applications handling user-generated content, API integrations, or complex object structures. Implementing data validation logic upfront can save significant time and debugging effort.

- [JavaScript Optional Chaining (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
- [Nullish Coalescing Operator (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)
- [Common JavaScript Errors Explained (Official Docs)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors)
