One of the most common runtime issues developers face in JavaScript is:
TypeError: Cannot read properties of undefined/null
This error happens when you try to access a property on a variable that is not defined or is set to null.
This guide explains why this error occurs, how to avoid it, and the best practices to fix it.
1. Understand Why This Error Happens
You will see this error when:
- Accessing a property of a variable that is
undefined - Accessing a property on a
nullvalue - Calling a function on something that isn’t defined
- Getting unexpected API responses or DOM elements
Example:
let user;
console.log(user.name); // ❌ user is undefined
2. Add Existence Checks
Before accessing a property, check if the object exists:
if (user && user.name) {
console.log(user.name);
}
This prevents JavaScript from reading a property on an invalid object.
3. Use Optional Chaining (?.)
Optional chaining is the cleanest way to prevent undefined errors:
console.log(user?.name);
Benefits:
- Avoids crashes
- Returns
undefinedinstead of throwing an error - Cleaner than using multiple
ifchecks
4. Use Default Values
JavaScript allows fallback values using || or ??.
Using || (falsy check)
let username = user?.name || "Guest";
Using ?? (nullish check)
let username = user?.name ?? "Guest";
Difference:
||considers'',0,falseas false??only checksnullorundefined
5. Debug with Console Logs
If you are unsure why a variable is undefined:
console.log("User =", user);
Identify:
- Is the variable declared?
- Is it assigned before usage?
- Is it coming from an API response?
- Is it misspelled?
6. Fix API Response Issues
Often, unexpected backend data causes undefined errors.
Example:
fetch('/api/user')
.then(res => res.json())
.then(data => console.log(data.profile.name));
Fix:
console.log(data?.profile?.name);
Always validate API responses before usage.
7. Fix DOM-Related Undefined Errors
Trying to access an element before it exists:
document.getElementById("box").innerText = "Hello";
Fix:
- Move script at end of body
- Or wrap in DOMContentLoaded
document.addEventListener("DOMContentLoaded", () => {
document.getElementById("box").innerText = "Hello";
});
8. Best Practices Summary
- Use optional chaining (
?.) - Use default values (
||or??) - Always check the existence of objects
- Validate API responses
- Log variables to trace undefined values
Following these steps will help you eliminate undefined/null value issues and write more stable JavaScript.
Citations
Internal: https://savanka.com/category/savanka-helps/
External: https://developer.mozilla.org/en-US/docs/Web/JavaScript