Quick Answer
Fix TypeError when accessing properties of undefined/null.
Understanding the Issue
This common error occurs when trying to access a property or method of an undefined or null value. It typically indicates incomplete initialization or missing data from API responses.
The Problem
This code demonstrates the issue:
Javascript
Error
const user = undefined;
console.log(user.name); // Cannot read property
const data = {};
console.log(data.user.profile); // Nested access fails
The Solution
Here's the corrected code:
Javascript
Fixed
// Solution 1: Optional chaining (ES2020)
console.log(user?.name);
console.log(data?.user?.profile);
// Solution 2: Guard clauses
if (user && user.name) {
console.log(user.name);
}
// Solution 3: Default objects
const safeUser = user || {};
console.log(safeUser.name);
Key Takeaways
Use optional chaining or proper checks for safe property access.