"TypeError: Cannot read properties of undefined (reading 'name')" means your code ran something.name while something was undefined. The fix is to find which value on the left of .name is undefined, using the line number in the stack trace, and work out why it was never set, rather than only silencing the error.
The error messages on this page were produced by running each snippet in Node.js 18.18 (the DOM example with a null stand-in for the element). Chrome and Edge use the same V8 engine and print the same messages.
Read the message correctly
const res = { data: {} };
console.log(res.data.user.name);
TypeError: Cannot read properties of undefined (reading 'name')
The word in brackets is the property being read, name. The undefined value is whatever comes immediately before it: res.data.user. People often check name or res, when the missing piece is in the middle of the chain.
The stack trace gives the file, line and column. Running a one-line script shows the format:
[eval]:1
let u; u.name
^
TypeError: Cannot read properties of undefined (reading 'name')
at [eval]:1:10
The caret points at the property access, and 1:10 is line 1, column 10. In a browser, click the file link in the DevTools Console to jump to that line. For long traces, see how to read a stack trace.
Find the undefined value in 30 seconds
Put a log or a breakpoint on the line just before the error and print each step of the chain:
console.log({ data: res.data, user: res.data?.user });
The first step that prints undefined is your culprit. In browser DevTools, a breakpoint on the failing line lets you hover over each part of the expression instead. Then ask the real question: where was that value supposed to come from?
The seven usual causes
1. The data has a different shape than you expected
The most common cause with APIs: the response nests things differently, or a key has another name.
const res = JSON.parse('{"data":{"items":[]}}');
console.log(res.data.results.length);
// Cannot read properties of undefined (reading 'length')
The API returns items, the code reads results. Log the actual response once (console.log(JSON.stringify(res, null, 2))) and match your code to it. Check error responses too: a 401 or 500 reply often has a completely different body.
2. Using data before it has loaded
Asynchronous data is undefined until the request finishes. In a UI framework, the first render happens before the fetch resolves:
// React: user is undefined on the first render
const [user, setUser] = useState();
return <h1>{user.name}</h1>; // crashes before the fetch completes
Either render a loading state first (if (!user) return <p>Loading…</p>;) or start with a value of the right shape. In plain JavaScript, make sure you await the promise before reading from its result.
3. An array lookup found nothing
const users = [{ id: 1, name: "Ana" }];
console.log(users.find(u => u.id === 2).name);
// Cannot read properties of undefined (reading 'name')
const arr = [];
console.log(arr[0].id);
// Cannot read properties of undefined (reading 'id')
find() returns undefined when nothing matches, and indexing past the end of an array returns undefined. Check the result before using it, and decide what "not found" should do.
4. The DOM element does not exist (null)
const el = document.querySelector("#total");
el.textContent = "42";
// TypeError: Cannot set properties of null (setting 'textContent')
MDN documents that querySelector() returns null "if there are no matches", so this variant says null, not undefined. Either the selector is wrong (a typo, a missing # or .), or the script ran before the element was parsed. A script in <head> runs before the body exists. Add defer to the script tag, which MDN describes as running the script "after the document has been parsed", or move the script to the end of <body>.
5. A method lost its this
class Counter {
constructor() { this.count = 0; }
inc() { this.count++; }
}
const c = new Counter();
const inc = c.inc;
inc();
// Cannot read properties of undefined (reading 'count')
Class bodies run in strict mode, so a method called without its object gets this === undefined. This happens when you pass a method as a callback, for example button.addEventListener("click", c.inc). Fix it with an arrow function (() => c.inc()) or c.inc.bind(c).
6. A function returned nothing
A function with no return, or a return on a branch that didn't run, returns undefined. A frequent version is an arrow function with braces: items.map(x => { x * 2 }) returns an array of undefined, because braces need an explicit return. Write x => x * 2 or x => { return x * 2; }.
7. A typo or a missing argument
JavaScript does not complain about reading a property that doesn't exist: config.setings.theme fails only at .theme, because config.setings is undefined. The same applies to a function called with fewer arguments than it expects. TypeScript, or the type checking in your editor, catches most of these before the code runs.
Related messages, same cause
| Code | V8 message (Chrome, Edge, Node.js) |
|---|---|
let o; o.x = 1; | Cannot set properties of undefined (setting 'x') |
let items; items.map(f) | Cannot read properties of undefined (reading 'map') |
const { a } = undefined; | Cannot destructure property 'a' of 'undefined' as it is undefined. |
const obj = {}; obj.load(); | obj.load is not a function |
const el = null; el.textContent | Cannot read properties of null (reading 'textContent') |
Other browsers word it differently. MDN lists TypeError: "x" is undefined for Firefox and TypeError: undefined is not an object (evaluating 'obj.x') for Safari.
When ?. and ?? are the right fix
If a missing value is a normal case, such as an optional field or a user without a profile picture, say so in the code. Optional chaining stops at the first null or undefined and returns undefined instead of throwing; nullish coalescing supplies a default:
const user = undefined;
console.log(user?.name ?? "anon"); // anon
const obj = {};
console.log(obj.load?.()); // undefined, no error
Two limits from MDN. First, ?. only guards against null and undefined: if obj.load exists but is not a function, obj.load?.() still throws "is not a function". Second, you cannot assign through it: obj?.prop = 1 is a SyntaxError.
Prefer ?? over || for defaults. || replaces every falsy value, including 0 and "":
const settings = { retries: 0 };
console.log(settings.retries || 3, settings.retries ?? 3); // 3 0
With ||, a deliberate setting of 0 retries silently becomes 3.
When the value should always be there, don't reach for ?.. It turns a clear crash at the source into an undefined that travels on and breaks something else later. Fix the cause, or fail with a clearer message:
if (!res.data?.user) {
throw new Error(`Expected data.user in /api/me response, got: ${JSON.stringify(res)}`);
}
If you still can't see it
Check whether the error comes from your code or from a library: the first stack frame that points into your own files is where the bad value was passed in. If the failing line is inside a minified bundle, turn on source maps in your build tool so the trace shows your original file and line. And if the value is undefined only sometimes, log it each time, because intermittent cases are almost always timing (cause 2) or data that differs between records (cause 1).
Frequently asked questions
- What does 'reading' mean in the error message?
- The name after 'reading' is the property your code tried to access, not the variable that was undefined. In user.profile.name with the message (reading 'name'), the undefined value is user.profile, the thing to the left of .name.
- What is the difference between 'Cannot read properties of undefined' and 'of null'?
- It tells you which empty value you got. undefined usually means a variable was never assigned, a property does not exist, or a function returned nothing. null is usually returned on purpose, for example by document.querySelector when no element matches.
- Should I just add ?. everywhere to stop the error?
- No. Optional chaining hides the crash but not the bug: the value is still missing, and the code continues with undefined, which often fails later in a less obvious place. Use ?. where a missing value is a normal, expected case, and fix the cause where it is not.
- Why does Safari or Firefox show a different message?
- Each JavaScript engine words the same TypeError differently. Chrome, Edge and Node.js (V8) say Cannot read properties of undefined (reading 'x'). Firefox says x is undefined, and Safari says undefined is not an object (evaluating 'obj.x'). The causes and fixes are identical.