TypeError: Cannot read properties of undefined (reading 'map')
Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.
Root Cause
One of the most frequent JavaScript runtime errors, this occurs when code attempts to access a property or call a method on a value that is undefined or null. In React and modern front-end applications this typically surfaces when component state has not been initialised with the correct shape, when an API response returns an unexpected structure, or when asynchronous data has not yet loaded by the time the render cycle executes. For example, calling response.data.items.map() will throw if response.data is undefined because the network request has not resolved yet. The root issue is an assumption that a nested object chain will always be fully populated, which is unsafe in asynchronous or dynamic environments. Defensive programming practices and proper state initialisation are the primary remedies.
Fix / Solution
Use optional chaining (?.) to safely navigate nested properties, provide default values via the nullish coalescing operator (??), and initialise state with the correct shape (e.g., an empty array [] instead of undefined). Always validate API response shapes before accessing nested fields.
Code Snippet
// ❌ Unsafe — crashes if data is undefined
const names = response.data.users.map(u => u.name);
// ✅ Safe — optional chaining + default
const names = response.data?.users?.map(u => u.name) ?? [];
// ✅ Even better — guard clause
if (!Array.isArray(response.data?.users)) {
console.warn("Unexpected API shape");
return [];
}
return response.data.users.map(u => u.name);