What does Cannot read properties of undefined mean in JavaScript?
Why the value is undefined
JavaScript returns undefined for missing object properties, uninitialized variables, and function arguments that were not passed. When you then try to read a property from that undefined value, the engine throws this error. The message usually names the property, such as reading 'name'.
This often happens with data from an API that changed shape, a state variable that loads after the first render, or a callback that runs before its result is ready. The error is a symptom, so the real bug is often earlier in the code.
- Check the variable right before the failing line
- Log the value to see when it becomes undefined
- Confirm that async data has loaded before use
How to fix it
Use optional chaining, such as user?.name, when a missing value is acceptable. Combine it with a fallback using the nullish coalescing operator, such as user?.name ?? 'Guest'. Use an explicit if check when missing data should trigger a different path.
Trace the value back to its source. If it comes from a fetch call, make sure the code waits for the response and handles the case where the shape is different than expected.
Common mistakes
- Adding optional chaining everywhere without finding why the value is missing.
- Assuming null and undefined are the same thing in every check.

Related questions
- What does NullPointerException mean in Java?
- How do I fix IndexError: list index out of range in Python?
- What does TypeError: 'NoneType' object is not subscriptable mean?
- Why do I get a segmentation fault in C?
- What does ValueError: could not convert string to float mean?
- How do I fix a stack overflow error?