TypeError: Cannot read properties of undefined (reading 'name')
TypeError: Cannot read properties of null (reading 'length')
This is the most common JavaScript error. It means youβre trying to access a property on something thatβs undefined or null.
Whatβs Happening
const user = undefined;
console.log(user.name); // π₯ TypeError!
You expected user to be an object, but itβs undefined. JavaScript canβt read .name on undefined.
Cause 1: API Response Not What You Expected
// β The API might return null or a different structure
const data = await fetch('/api/user').then(r => r.json());
console.log(data.user.name); // π₯ if data.user is undefined
Fix: Check before accessing:
// Optional chaining (modern JS)
console.log(data?.user?.name);
// Or explicit check
if (data && data.user) {
console.log(data.user.name);
}
Cause 2: Accessing State Before Itβs Set (React)
// β On first render, user is undefined
const [user, setUser] = useState();
return <h1>{user.name}</h1>; // π₯
Fix: Default value or conditional render:
const [user, setUser] = useState(null);
return <h1>{user?.name || 'Loading...'}</h1>;
// Or guard the render
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
Cause 3: Array Index Out of Bounds
const items = [];
console.log(items[0].name); // π₯ items[0] is undefined
Fix:
console.log(items[0]?.name);
// Or check length first
if (items.length > 0) {
console.log(items[0].name);
}
Cause 4: Typo in Property Name
const config = { database: { host: 'localhost' } };
console.log(config.databse.host); // π₯ typo: "databse"
Fix: Use TypeScript. It catches typos at compile time. Or use console.log(config) to see the actual structure.
Cause 5: Async Timing Issue
let data;
fetch('/api').then(r => r.json()).then(d => { data = d; });
console.log(data.name); // π₯ fetch hasn't completed yet
Fix: Use await or handle the data inside the callback:
const data = await fetch('/api').then(r => r.json());
console.log(data.name); // β
Cause 6: Destructuring Something Undefined
// β If props.user is undefined
const { name, email } = props.user; // π₯
Fix: Default value:
const { name, email } = props.user || {};
// Or
const { name, email } = props.user ?? {};
The Universal Fix: Optional Chaining
Optional chaining (?.) is the single best tool for preventing this error:
// Instead of:
if (obj && obj.a && obj.a.b && obj.a.b.c) { ... }
// Write:
const value = obj?.a?.b?.c;
It returns undefined instead of throwing an error. Works in all modern browsers and Node.js 14+.
Debugging Tips
- Read the error message carefully β it tells you which property it tried to read (
reading 'name') - Add
console.logbefore the error line β check what the variable actually is - Use the browser debugger β set a breakpoint and inspect variables
- Use TypeScript β it catches most of these errors before runtime