Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Keenan Constance
The "Cannot read property 'forEach' of undefined" error occurs when the
forEach()
method is called on an undefined
value. To solve the error, make
sure to only call the forEach
method on arrays, Set or Map objects.
Here is an example of how the error occurs.
const arr = undefined; // ⛔️ Cannot read properties of undefined (reading 'forEach') arr.forEach(element => { console.log(element); });
Because we called the forEach
method on an undefined
value, we got the error
back.
Instead, initialize the value for the variable to the correct data type before
calling the forEach
method.
const fromDb = undefined; // ✅ Initialize to empty array if falsy const arr = fromDb || []; // ✅ Using optional chaining arr?.forEach(element => { console.log(element); }); // ✅ Check if truthy if (arr) { arr.forEach(element => { console.log(element); }); } // ✅ Check if Array if (Array.isArray(arr)) { arr.forEach(element => { console.log(element); }); }
We used the logical OR (||) operator to provide a fallback value if the value to
the left is falsy (e.g. undefined
).
The next example shows how to use the
optional chaining (?.)
operator. The operator short-circuits returning undefined
if the reference is
equal to null
or undefined
.
if
statement to check if the arr
variable stores a truthy value. Since undefined
is falsy, it wouldn't pass the test.The last example shows how to use the Array.isArray
method to check if the
variable stores an array.
The forEach
is implemented for multiple data structures:
If you're using the method with arrays, you can use the optional chaining
operator or the Array.isArray
method to only call the forEach
method on a
valid array.
Otherwise, you can use the if
statement with the truthy check, since all
arrays, Map and Set objects are truthy values.
The "Cannot read property 'forEach' of undefined" error often occurs when trying to access an array index that doesn't exist.
const arr = []; // ⛔️ Cannot read properties of undefined (reading 'forEach') arr[0].forEach(element => { console.log(element); });
We are accessing an empty array at index 0
, which returns undefined
, on
which we call the forEach
method and get the error.
If you're unsure the index exists in the array, you can use the optional chaining operator.
const arr = []; arr[0]?.forEach(element => { console.log(element); });
The optional chaining (?.) operator won't invoke the forEach
method because
accessing the array at index 0
returns an undefined
value.
The "Cannot read property 'forEach' of undefined" error occurs when calling the
forEach
method on an undefined
value.
To solve the error make sure to initialize the variable to the correct value and
only call the forEach
method on the correct data type.