# TypeError: Cannot read properties of undefined (reading 'x')

**Code:** `TypeError` · **Category:** JavaScript · **Seen on:** JavaScript, React, Node.js

You tried to access a property on a value that is `undefined` (or `null`) — usually data that hasn’t loaded yet or a wrong property path.

## Meaning

JavaScript throws this when the left side of `.` or `[]` is `undefined` or `null`. The name in parentheses is the property you tried to read, not the variable that was undefined. In `user.profile.name`, “reading 'name'” means `user.profile` was undefined.

Older browsers phrase it as “Cannot read property 'x' of undefined” and Safari as “undefined is not an object (evaluating …)”.

## Common causes

- Async data not loaded yet (rendering before fetch completes)
- Wrong property name or path (typo, different API shape)
- Array index out of range (`items[5]` when there are 3 items)
- Function returns nothing (missing `return`)
- DOM element not found — `document.querySelector()` returned null
- Destructuring from undefined (`const { a } = props.data`)

## Quick fix

1. Find the exact line from the stack trace and log the object just before it
2. Use optional chaining: `user?.profile?.name`
3. Provide defaults: `const items = data?.items ?? []`
4. Render a loading state until async data exists
5. Run DOM code after the element exists (`defer`, `DOMContentLoaded`)

## Detailed fix by platform

### JavaScript

1. Guard the access:

```javascript
// ❌ crashes when data or data.items is undefined
const names = data.items.map(i => i.name);
// ✅
const names = (data?.items ?? []).map(i => i.name);
```


### React

1. Handle the loading state:

```jsx
const [users, setUsers] = useState([]);        // start with an empty array, not undefined
useEffect(() => { fetch('/api/users').then(r => r.json()).then(setUsers); }, []);
if (!users.length) return <p>Loading…</p>;
return users.map(u => <li key={u.id}>{u.name}</li>);
```


### Node.js

1. Check API responses before use: `if (!res.data?.user) throw new Error('User missing in response')` gives a clearer error at the source.

## Code examples

### Read the stack trace

```text
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
    at UserList (UserList.jsx:14:23)
```

Line 14, column 23 of UserList.jsx: whatever is before `.map` is undefined.

## How to diagnose

1. **Stack trace** — Which file:line, and which property is being read?
2. **Object** — Log the value left of the dot — undefined or null?
3. **Source** — Where should it come from — API, props, state, DOM?
4. **Timing** — Is it accessed before it’s ready?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/javascript/typeerror-cannot-read-properties-of-undefined)
