Bugs

TypeError: Cannot Read Properties of Undefined in JavaScript

This is one of the most common JavaScript errors. It occurs when code tries to access a property on a value that is undefined or null.


❌ Code Causing TypeError

async function displayUser(userId) {
  const user = await fetchUser(userId);
  // fetchUser returns undefined if not found
  console.log(user.name);  // TypeError if user is undefined!
  console.log(user.address.city);  // Nested crash risk
}

✅ Fixed with Optional Chaining

async function displayUser(userId) {
  const user = await fetchUser(userId);
  if (!user) { console.log('User not found'); return; }
  console.log(user.name);
  console.log(user?.address?.city ?? 'No city on record');
}
💡

Pro tip: Use optional chaining (?.) to safely access nested properties. Use ?? to provide fallback values for null/undefined.

Paste this code into LearnCodeGuide

Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze JavaScript Code →

Related Guides

Javascript Equality Operator BugsTypescript Null Undefined ErrorsPython None Type Error