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.
| Message | Usual cause | Fix |
|---|---|---|
| reading 'map' | Array from an API not loaded yet | Start state as [] or render a loading state |
| of null (reading 'addEventListener') | Script ran before the element existed | Add defer to the script tag |
| reading 'length' | Variable never assigned | Default it, for example value ?? '' |
| reading 'data' | Response shape differs from what you expected | Log the response and match its real keys |
| reading 'params' in a route | Component used outside its router | Wrap 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
- Click the file and line in the console stack trace.
- Find the expression just before the named property and log it.
- Decide why it is empty: timing, a typo, a missing element or a different data shape.
- 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
- Build a Car Dealership Website: Pages, Costs and a Working Example | How-to Guide
- Careers Page Examples
- What a CDN Does, Explained Plainly
- Contact Us Page Examples: 6 Small-Business Designs Annotated | How-to Guide
- Content Approval Workflow for Websites: Who Signs Off, When, and How to Stop It Becoming a Bottleneck | How-to Guide
- Cookie Consent Banner Examples You Can Copy
- Copy to Clipboard Button (JavaScript and React)
- Core Web Vitals: LCP, INP and CLS, with 25 Fixes
Product
Who It's For
- For Agencies
- For Freelancers
- For Hosting Providers
- For SaaS Platforms
- For Startups
- For Financial Services
- For Healthcare
Features
Resources
- Blog
- Help Center
- Free Business Tools
- Free UI Components
- Website Templates
- Template Collections
- Website Examples
- Guides
- Comparisons
- Alternatives
- Best Lists
- Reviews
- Pricing Guides
- Use Cases
- Glossary & Guides
- Integrations
- Developers
- Benchmark
- Windows App