StackDevLife
1-Min FixBeginnerJavaScript

Fix “Cannot read properties of undefined” instantly

~1 min read
TL;DR

This error happens when you access a property on undefined. Use optional chaining to fix it quickly.

This is one of the most common JavaScript errors:

TypeError: Cannot read properties of undefined

It usually happens when you're trying to access a nested property that doesn’t exist.

Example:

JavaScript
const user = {};
console.log(user.profile.name);

This will crash because profile is undefined.

Quick fix using optional chaining:

JavaScript
const user = {};
console.log(user.profile?.name);

Now it safely returns undefined instead of crashing.

Bonus tip:
You can also provide a default value:
console.log(user.profile?.name || "Guest");

Use optional chaining whenever dealing with uncertain data (API responses, user input, etc.)

JavaScriptError-Fixoptional-chainingFrontend

Get a new 1-Min Fix in your inbox

Subscribe to Stack Dev Life — free, no spam, unsubscribe anytime.

Subscribe free →