How do I fix "Cannot read properties of undefined"?
Something you expected to be an object is undefined. Read the property name in the error, find where that value comes from, and either guard it with ?. or fix why it is missing.
const user = { name: 'Dom' };
console.log(user.address.city);
// TypeError: Cannot read properties of undefined (reading 'city')The message names city, so the thing that is undefined is user.address — one step to the left of the named property. That is the trick to reading it quickly.
#The usual causes
A DOM element that is not there yet:
document.querySelector('.missing').textContent = 'x';querySelector returns null when nothing matches. Either the selector is wrong, or the script ran before the element existed — load scripts with defer, or place them at the end of <body>.
API data shaped differently than expected. console.log the whole response before reaching into it.
An array index that does not exist. items[5] on a three-item array is undefined.
A typo. respose.data reads a property that was never set.
#Optional chaining
const city = user.address?.city; // undefined, no crash
const first = items?.[0];
const result = callback?.();Combine it with a default:
const city = user.address?.city ?? 'Unknown';#undefined vs null
undefined means never assigned. null means deliberately empty. If an API returns null, ?. still short-circuits — it checks for both.