DEV3 Technologies home

DEV3 Developer Forum

How do I debug 'TypeError: Cannot read properties of undefined (reading ...)' in JavaScript?

JavaScript helpSolved0 views
dev3 ·

My app crashes with TypeError: Cannot read properties of undefined (reading 'map'). What does it mean and what is a systematic way to fix it?

#javascript#errors#debugging

0

1 reply

dev3 · Accepted answer

It means you wrote something.prop where something is undefined (or null). The word in parentheses is the property you tried to read, which tells you what to look for: reading 'map' means x.map(...) where x is undefined.

Step 1: find which value

Read the stack trace top line (file and line). Log the object just before:

console.log({ items });

or set a breakpoint in DevTools.

Step 2: understand why it is undefined

Typical causes:

  1. Async data not loaded yet: React state starts as undefined, the first render runs before the fetch finishes.
  2. Wrong shape: API returns { data: { items } } but you read res.items.
  3. Typo or case difference: user.Name vs user.name.
  4. Missing return: a function without return yields undefined.
  5. Array index out of range: arr[5].name.
  6. this lost in callbacks (see the this rules).
  7. Environment: a variable not set, JSON.parse of something else.

Step 3: fix at the right place

// default the state
const [items, setItems] = useState([]);

// guard rendering
{items?.map((i) => <Row key={i.id} {...i} />)}

// default while destructuring
const { items = [] } = response ?? {};

Also render a loading state explicitly instead of hiding bugs with ?. everywhere.

Prevent it

  • TypeScript with strict flags these at compile time.
  • Validate API responses with a schema.
  • Use optional chaining only where undefined is a legitimate state.

Pitfall: a try/catch that swallows the error and continues leaves your app in a half-broken state. Fix the cause.

If the data comes from JSON, the JSON formatter helps confirm the real shape.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.