Cannot Read Properties of Undefined: Why and How to Fix

JavaScript throws Cannot read properties of undefined (or of null) when code reads a property from a value that does not exist yet. The part in brackets, such as reading 'map', names the property; the value to its left is the missing one. Usually data has not loaded, a key is misspelled, or an element was not found.

Common versions of the error
MessageUsual causeFix
reading 'map'Array from an API not loaded yetStart state as [] or render a loading state
of null (reading 'addEventListener')Script ran before the element existedAdd defer to the script tag
reading 'length'Variable never assignedDefault it, for example value ?? ''
reading 'data'Response shape differs from what you expectedLog the response and match its real keys
reading 'params' in a routeComponent used outside its routerWrap it in the router or pass props

Updated

Older Chrome versions phrased it as Cannot read property 'x' of undefined; the meaning is unchanged. The stack trace gives the file and line. Put a breakpoint or console.log there and inspect the object one step to the left of the property named in the message.

Guards and timing fixes

Optional chaining and defaults

?. returns undefined instead of throwing; ?? supplies a fallback.

const city = user?.address?.city ?? "Unknown";
const names = (data?.items ?? []).map((i) => i.name);

React: start with an empty array

The first render now maps over [] instead of undefined.

const [posts, setPosts] = useState([]);

useEffect(() => {
  fetch("/api/posts").then((r) => r.json()).then(setPosts);
}, []);

return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;

Run the script after the HTML is parsed

defer waits for the document, so getElementById finds the button.

<script src="/app.js" defer></script>

Timing problems

Scripts in the head run before the body exists. Add defer, move the script to the end of body, or listen for DOMContentLoaded. In frameworks, read DOM nodes in an effect or a ref callback, never during the first render.

Async data has the same shape problem. Render a loading state until the request finishes, and an empty state when it returns nothing, instead of assuming the data is there.

Shape problems

Log the whole object and compare its keys with your code. APIs often wrap results, so the list you want is response.data.items rather than response.items. Case matters too: userId and userID are different keys.

If you would rather not debug front-end code for a simple business site, We.Inc generates the pages for you and checks them in a preview before anything goes live.

How it works

  1. Click the file and line in the console stack trace.
  2. Find the expression just before the named property and log it.
  3. Decide why it is empty: timing, a typo, a missing element or a different data shape.
  4. Fix the cause, or guard the read with optional chaining and a default.

Tips

  • Optional chaining stops the crash, but an empty screen with no error can be worse. Guard the read and also handle the empty case visibly.
  • document.querySelector returns null when the selector matches nothing, so a typo in a class name produces the null version of this error.
  • In React, the first render happens before useEffect fetches anything. Initial state of undefined plus .map in JSX crashes immediately.
  • Deeply nested API data changes over time. Validate it at the boundary with a schema library instead of trusting every key.

Frequently asked questions

What does cannot read properties of undefined mean?

Code tried to access a property, such as .map or .name, on a value that is undefined. Undefined has no properties, so JavaScript throws a TypeError and stops that code path.

How do I fix cannot read properties of undefined (reading 'map')?

Make sure the array exists before mapping. Initialize state as an empty array, check the API response really contains the array, or write items?.map(...) while it loads.

Why do I get cannot read properties of null (reading 'addEventListener')?

getElementById or querySelector found no element, so it returned null. Either the script runs in the head before the HTML loads, fixed with defer, or the id or selector does not match.

What is the difference between undefined and null here?

Undefined usually means something was never set or a key does not exist. Null usually comes from an API that deliberately returns nothing, most often a DOM lookup that found no element.

Related: Data fetching in React, JavaScript event listeners, JavaScript objects, TypeError: Failed to fetch.

Start for free or see all free tools. We.Inc is free to start, with no card needed. AI building is on paid plans from $20 a month.

More in Guides

Product

Who It's For

Features

Resources

Company

View Sitemap