TypeError: Cannot read properties of undefined (reading 'x')
"Cannot read properties of undefined" is a JavaScript TypeError thrown when code reads a property from a value that is undefined: in obj.user.name, if obj.user is undefined, reading name throws. The name in (reading 'x') is the property you tried to read, not the variable that was undefined; that is the expression just to its left. Fix it by finding why that value is missing (data not loaded yet, a wrong key, a missing return) and either make sure it exists or guard the access with optional chaining (?.) and a default.
Steps
- Read the property nameNote the name in (reading 'x'): the value just before it in the expression is the one that was undefined.
- Open the exact lineUse the stack trace, with source maps in production, to find the file, line and column.
- Check the real dataInspect the actual API response or variable at that point, including loading and error states.
- Fix the sourceCorrect the key, add the missing return or await, or handle the loading state where the value is created.
- Guard only legitimate gapsUse ?. and ?? where missing data is expected, and throw a clear error where it is not.
The exact messages, by browser
Chrome, Edge, Node.js and other V8-based runtimes print:
TypeError: Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of null (reading 'map')
TypeError: Cannot read properties of undefined (reading '0')The last one is an array index: rows[0] where rows is undefined. The null variant is the same bug with a null value, often from document.querySelector() or a JSON field set to null. Writing instead of reading gives TypeError: Cannot set properties of undefined (setting 'x').
In the browser console an error nobody caught is prefixed Uncaught TypeError: …; inside a rejected promise it is Uncaught (in promise) TypeError: …. Same error, different path (see unhandled promise rejection). Older Chrome and Node versions printed Cannot read property 'length' of undefined.
Other engines word it differently, per MDN:
| Engine | Message |
|---|---|
| V8 (Chrome, Edge, Node) | TypeError: Cannot read properties of undefined (reading 'x') |
| Firefox | TypeError: "x" is undefined |
| Safari (WebKit) | TypeError: undefined is not an object (evaluating 'obj.x') |
If your error tracker groups by message, one bug can show up as several issues, one per browser.
Causes, most common first
- Data not loaded yet. A component renders before a fetch resolves, so
data.items.lengthruns whiledataordata.itemsis still undefined. The classic(reading 'length')and(reading 'map'). - The API response changed shape. The backend renamed
itemstoresults, or returns an error body ({"error": "…"}) with a 200, and the code reads fields that are not there. - Wrong key or typo.
user.adress.city, or camelCase vs snake_case (user.first_namevsfirstName). - Empty array or missing index.
results[0].idwhenresultsis[]:results[0]is undefined. - A function with no return. An arrow function with braces (
x => { x * 2 }) or a missedreturnin one branch returns undefined. - Lost
this. A class method passed as a callback (button.onclick = this.save) runs withthisundefined, sothis.statethrows. - Missing
await.const user = getUser(); user.profilereads from a Promise, which gives undefined, and the next read throws.
Find which value was undefined
The message names the property being read; the undefined value is whatever sits just before it. In this line, (reading 'length') means one of two things was undefined:
const count = response.data.items.length;
// (reading 'items') -> response.data is undefined
// (reading 'length') -> response.data.items is undefinedThen work backwards: log or break on the line, check where that value was assigned, and look at the real payload in the network tab, not the one you expected. If several reads on one line share the same property name, the column number in the stack frame tells you which one.
Fix it properly
Make sure the value exists before the code that needs it runs, and guard only where missing data is a legitimate state:
// Before
function OrderList({ data }) {
return <p>{data.items.length} orders</p>;
}
// After: loading is a real state, so handle it
function OrderList({ data }) {
if (!data) return <p>Loading…</p>;
const items = data.items ?? [];
return <p>{items.length} orders</p>;
}Optional chaining short-circuits to undefined instead of throwing when the value before ?. is undefined or null; pair it with ?? for a default: const n = data?.items?.length ?? 0;. It can't be used on the left of an assignment (obj?.x = 1 is a SyntaxError).
The mistake people make next is sprinkling ?. everywhere. The TypeError disappears, but the page now shows "0 orders" for a broken API response, and nothing reports it. Guard values that may truly be missing; for values that must exist, validate the response at the boundary and throw a clear error (throw new Error('orders API: missing items')) that your error tracker will group and you will understand.
How it looks in Sentry
Sentry shows the error type and message as the issue title, for example TypeError: Cannot read properties of undefined (reading 'length'), with the browser, OS and URL as tags. In production bundles the stack frames point into minified files like main.4f2a1c.js at line 1, column 48211, which tells you nothing. To get readable stack traces you have to upload source maps; Sentry's recommended setup is the wizard:
npx @sentry/wizard@latest -i sourcemapsBy default Sentry links source maps by injecting Debug IDs into your build output, so the uploaded maps match the exact files you deployed. With them in place the frame shows your original file, function and line, and the column points at the exact property read. Breadcrumbs show the fetch or click that came just before, which is usually the answer to "why was it undefined". More in Sentry source maps.
Questions
What does "cannot read properties of undefined (reading 'length')" mean?
Your code called .length on something that was undefined, usually an array or string that hadn't loaded yet or a field that doesn't exist on the object.
What does "Uncaught TypeError: Cannot read properties of undefined" mean?
It is the same error; Uncaught means no try/catch handled it, so it reached the top level and was reported in the console.
Is it different from "Cannot read properties of null"?
Same bug, different empty value: the variable was null instead of undefined. DOM lookups and JSON fields set to null are the usual source.
Why does Safari show a different message for the same error?
Each engine words TypeErrors its own way. Safari says "undefined is not an object (evaluating 'obj.x')" and Firefox says "x" is undefined for the same bug.
Sources
- TypeError: "x" is (not) "y"developer.mozilla.org
- Optional chaining (?.)developer.mozilla.org
- Source Mapsdocs.sentry.io