Fix "Cannot read properties of undefined" in JavaScript
TypeError: Cannot read properties of undefined (reading 'map')
- TypeError: Cannot read property 'map' of undefined
- TypeError: Cannot read properties of null (reading 'addEventListener')
- TypeError: undefined is not an object (evaluating 'data.items')
- TypeError: can't access property "map", data.items is undefined
- TypeError: data is undefined
You are reading a property (here map) on a value that is undefined or null. The object before the dot does not exist yet or does not have the expected shape: check where it comes from, then guard the access with ?. and a default value ?? [].
What this error means
In JavaScript, only objects (and boxed primitives) have properties. When the engine evaluates data.items.map, it first reads data.items; if that value is undefined or null, it cannot look up map on it and throws a TypeError. The name in parentheses is the property you tried to read, not the missing one: the culprit is always the expression just to its left. Chrome, Edge and Node.js (V8) print "Cannot read properties of undefined (reading 'x')", Firefox prints "x is undefined" and Safari "undefined is not an object". The stack trace gives the exact file and line.
Common causes
- Async data not loaded yet: on the first render (React, Vue) or before a
fetchresolves, the variable is stillundefined. - API response shaped differently than expected: the array lives in
data.resultsinstead ofdata.items, or the API returns an error{ "message": ... }instead of the data. - DOM element not found:
document.querySelector()returnsnullbecause the selector is wrong or the script runs before the HTML is parsed. - Missing index or key:
users[5].namewhen the array only has 3 items, or a misspelled key. - Lost
this: a method passed as a callback withoutbindor an arrow function, sothisisundefinedin strict mode.
Step-by-step fix
-
Find the failing expression
Open the line shown in the stack trace. In
a.b.c.map, theundefinedvalue is the one right beforemap. Add aconsole.logjust before it to see its real value.console.log('data =', data); console.log('items =', data?.items); -
Check the real data shape
In the DevTools Network tab, open the API response and compare its keys with the ones in your code. Paste the JSON into a formatter to read its structure easily.
-
Guard the access with
?.and??Optional chaining
?.returnsundefinedinstead of throwing, and??provides a default value. This is the most common fix for data that may be missing.const items = data?.items ?? []; const names = items.map((item) => item.name); -
Initialize state and handle loading (React)
Give state a consistent initial value (
[]for a list) and render a loading state until the data has arrived.const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { fetch('/api/users') .then((res) => res.json()) .then((data) => setUsers(data.users ?? [])) .finally(() => setLoading(false)); }, []); if (loading) return <p>Loading...</p>; return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>; -
Wait for the DOM before using it
If the error comes from
querySelector, load the script withdeferor wait forDOMContentLoaded, and check the element exists before using it.document.addEventListener('DOMContentLoaded', () => { const button = document.querySelector('#save'); if (!button) return; button.addEventListener('click', save); });
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Enable TypeScript with
"strict": true: the compiler flags access to possiblyundefinedvalues before runtime. - Validate API responses at the boundary (for example with Zod) instead of assuming their shape everywhere in the code.
- Always initialize state and variables with a value of the right type (
[],{},'') instead of leaving themundefined.
Frequently asked questions
What is the difference between "Cannot read property of undefined" and "Cannot read properties of undefined"?
It is the same error. V8 (Chrome 91+, Node.js 16.9+) simply changed the wording to "Cannot read properties of undefined (reading 'x')".
Why does my React component crash on first render even though the data arrives?
The first render happens before the fetch resolves, so state still holds its initial value. Initialize it with [] or render a loading state.
Should I put ?. everywhere to avoid this error?
No. Use it where a value can legitimately be missing. Elsewhere, a visible error helps you spot a real bug instead of hiding it.
Useful tools for this error
More JavaScript & Node.js errors
- Fix "blocked by CORS policy: No 'Access-Control-Allow-Origin' header"
- Fix "Unexpected token '<', "<!DOCTYPE "... is not valid JSON"
- Fix "Error: Cannot find module" in Node.js
- Fix "npm ERR! ERESOLVE unable to resolve dependency tree"
- Fix "Hydration failed because the server rendered HTML didn’t match the client" (React, Next.js)
- Fix "Too many re-renders. React limits the number of renders" in React
- Fix "Error: listen EADDRINUSE: address already in use" in Node.js
- Fix "SyntaxError: Cannot use import statement outside a module"