How to Fix JavaScript TypeError: Cannot Read Property
DodaTech
1 min read
In this tutorial, you'll learn about How to Fix JavaScript TypeError: Cannot Read Property. We cover key concepts, practical examples, and best practices.
The Problem
You run JavaScript code and get:
TypeError: Cannot read properties of undefined (reading 'name')
Or:
TypeError: Cannot read properties of null (reading 'length')
This occurs when you try to access a property or call a method on null or undefined. The variable exists but holds a falsy value that does not have the expected property.
Quick Fix
Step 1: Find where the value is set
The error includes the variable or expression that is null/undefined. Search your code for where that value comes from:
// The error says 'name' is undefined
const user = getUser(); // Might return undefined
console.log(user.name); // TypeError
Step 2: Use optional chaining (ES2020)
// Before
const name = user.name;
// After -- returns undefined instead of throwing
const name = user?.name;
Optional chaining works for nested access too:
const city = user?.address?.city ?? "Unknown";
Step 3: Add default values with nullish coalescing
const name = user?.name ?? "Guest";
const count = items?.length ?? 0;
Step 4: Add defensive checks
if (user && user.name) {
console.log(user.name);
} else {
console.log("User or name is missing");
}
Alternative Solutions
Use a utility function for deeply nested access:
function get(obj, path, defaultValue) {
const keys = path.split(".");
let result = obj;
for (const key of keys) {
if (result == null) return defaultValue;
result = result[key];
}
return result ?? defaultValue;
}
Prevention
- Validate API responses before accessing nested properties.
- Use TypeScript to catch null/undefined access at compile time.
- Initialize variables with sensible defaults.
- Use optional chaining
?.and nullish coalescing??as default patterns.
← Previous
How to Fix JavaScript SyntaxError: Unexpected token
Next →
How to Fix JavaScript TypeError: Cannot read properties of undefined
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro