How to Resolve "TypeError: Cannot read properties of undefined (reading 'forEach')" Error in JavaScript
The TypeError: Cannot read properties of undefined (reading 'forEach') is a common error in JavaScript that occurs when you attempt to call the .forEach() method on a variable that is not an array (or another iterable type like a Map or Set). The error message is explicit: your code tried to find the forEach property on a value that was undefined.
This guide will explain what the .forEach() method is, why you might be getting this error, and provide the standard, robust solutions to fix it, from providing fallback values to using modern optional chaining.
Understanding the .forEach() Method
The .forEach() method is a function that exists on arrays (and other iterable objects like Map and Set). It is used to execute a function once for each element in the array.
Example of correct usage:
const fruits = ['apple', 'banana', 'cherry'];
// This works because `fruits` is an array.
fruits.forEach(fruit => {
console.log(fruit);
});
Output:
apple
banana
cherry
Understanding the Error: Why undefined?
The error Cannot read properties of undefined (reading 'forEach') happens when the variable you are calling .forEach() on is not an array, but is instead undefined.
Example of error:
let myList; // This variable has been declared but not initialized.
console.log(myList);
// Output: undefined
// The .forEach() method does not exist on `undefined`.
// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')
myList.forEach(item => {
console.log(item);
});
::: note This error commonly occurs when:
- A variable is declared but never assigned a value.
- A function that was expected to return an array returns
undefinedinstead. - You try to access a property on an object that doesn't exist. :::
Solution 1: Provide a Fallback to an Empty Array
If a variable might be undefined (for example, if it's coming from an API response or a function that can fail), the simplest way to prevent the error is to provide an empty array ([]) as a fallback.
This is often done using the logical OR (||) operator.
const dataFromApi = undefined;
// If dataFromApi is falsy (like undefined), use an empty array instead.
const items = dataFromApi || [];
// ✅ This is now safe. The .forEach() method is called on an empty array,
// so the loop simply does nothing. No error is thrown.
items.forEach(item => {
console.log('This will not run, but it will not crash.');
});
This is a very common and effective pattern for ensuring a variable is always iterable.
Solution 2: Use a Conditional Check Before Looping
A more explicit and often more readable solution is to check if the variable is actually an array before you attempt to loop over it. The Array.isArray() method is the perfect tool for this.
const myList = undefined;
// The Array.isArray() method returns true only if the value is an array.
if (Array.isArray(myList)) {
myList.forEach(item => {
console.log(item);
});
} else {
console.log('Cannot loop, because myList is not an array.');
}
// Output: Cannot loop, because myList is not an array.
This approach makes your code very robust and its intent clear. It prevents the error by ensuring the .forEach() loop is only ever attempted on a valid array.
Solution 3: Use Optional Chaining (?.) for a Concise Guard
For modern JavaScript (ES2020 and newer), the optional chaining operator (?.) is the most concise and elegant solution. It allows you to attempt to call a method on a value. If the value is null or undefined, the expression will stop ("short-circuit") and return undefined instead of throwing an error.
const myList = undefined;
// ✅ This is safe. The `?.` checks if `myList` is null or undefined.
// Since it is, the .forEach() call is never made, and no error occurs.
myList?.forEach(item => {
console.log(item);
});
console.log('The script continues without crashing.');
This is the recommended modern syntax for safely calling methods on variables that might not exist. It is especially useful when dealing with nested objects or arrays.
Conclusion
The Cannot read properties of undefined (reading 'forEach') error is a clear signal that you are trying to iterate over a variable that is not an array.
To fix it, you must ensure your variable is an array before calling .forEach():
- Provide a Fallback: Use the logical OR operator to default to an empty array:
const items = data || [];. This is a quick and common fix. - Use a Conditional Check (Best for Clarity): Use
if (Array.isArray(items))to guard your loop, making your code explicit and robust. - Use Optional Chaining (Best for Conciseness): Use
items?.forEach(...)for a clean, modern, and safe way to call the method on a potentiallyundefinedvalue.