The “forEach is not a function” error occurs when we call the forEach() method on a value that is not of type array, Map, or Set. To solve the error, make sure to only call the forEach method on arrays, Map or Set objects.

Here are 2 examples of how the error occurs:
// with DOM elements
const boxes = document.getElementsByClassName('box');
console.log(boxes); // [div.box, div.box, div.box]
// Uncaught TypeError: boxes.forEach is not a function
boxes.forEach(element => {
console.log(element);
});
// with Objects
const obj = {};
// Uncaught TypeError: obj.forEach is not a function
obj.forEach(element => {
console.log(element);
});
In the first example we use the getElementsByClassName method to get an array-like object, try to call the Array.forEach method on it and get the error.
The second example calls the forEach method on an object, and since it’s not implemented on objects, we get back the error.
Here are the solutions for both scenarios.
// with DOM elements
const boxes = document.getElementsByClassName('box');
console.log(boxes); // [div.box, div.box, div.box]
Array.from(boxes).forEach(element => {
console.log(element);
});
// with Objects
const obj = {name: 'Tom', country: 'Chile'};
Object.keys(obj).forEach(key => {
console.log(key); // "name", "country"
console.log(obj[key]); // "Tom", "Chile"
});
We used the Array.from method to convert the array-like object to an array before calling the forEach() method.
In the second example, we used the Object.keys()
method to get an array of the object’s keys before calling the forEach
method to iterate over the array.
Alternatively, you could check if the value is of the correct type before calling the forEach method.
const arr = null;
if (Array.isArray(arr)) {
arr.forEach(element => {
console.log(element);
});
}
We used the Array.isArray method to check if the arr variable stores an array. Then, we only call the forEach method if the variable stores an array.
If the “forEach is not a function” error still persists, console.log the value you’re calling the forEach method on and make sure the value is an array, Map or a Set, depending on your use case.
If the value is fetched from a remote server, make sure you have parsed the JSON to a native JavaScript array before calling the forEach method.