TypeError: .foreach is not a function
occurs when we call foreach()
function on object which is not array
, Set
or Map
. To resolve this issue, you can use Object.keys()
rather than directly calling foreach()
on object or use Array.from()
to convert array like object to array.
In other words, call foreach()
method only on iterable objects such as arrays
, Map
or Set
.
Let’s see multiple examples.
Use Object.keys() or Object.values() or Object.entries()
If you are getting this error on object, you can use Object.keys()
or Object.values()
or Object.entries()
and call forEach()
on array returned by these methods.
1 2 3 4 5 6 7 8 9 10 |
const empObj = { name: 'Mary', age: 30, }; empObj.forEach(e => { console.log(e); }); |
You will get following error when you execute the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
empObj.forEach(e => { ^ TypeError: empObj.forEach is not a function at Object.<anonymous> (HelloWorld.js:7:8) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11 |
We got this error because we can’t directly call forEach()
on any object
To resolve this issue, use Object.keys() to get keys array and call forEach() on keys.
1 2 3 4 5 6 7 8 9 10 11 12 |
const empObj = { name: 'Mary', age: 30, }; console.log(Object.keys(empObj)); Object.keys(empObj).forEach(key => { console.log(key +" - "+ empObj[key]); }); |
Output:
1 2 3 4 5 |
[ 'name', 'age' ] name - Mary age - 30 |
If you are just interested in values, you can use Object.values().
1 2 3 4 5 6 7 8 9 10 11 12 |
const empObj = { name: 'Mary', age: 30, }; console.log(Object.values(empObj)); Object.values(empObj).forEach(value => { console.log(value); }); |
Output:
1 2 3 4 5 |
[ 'name', 'age' ] name - Mary age - 30 |
If you need both key and value in an array, then you can use Object.entries().
1 2 3 4 5 6 7 8 9 10 11 12 |
const empObj = { name: 'Mary', age: 30, }; console.log(Object.entries(empObj)); Object.entries(empObj).forEach(([key, value]) => { console.log(key+" - "+value); }); |
Output:
1 2 3 4 5 |
[ [ 'name', 'Mary' ], [ 'age', 30 ] ] name - Mary age - 30 |
Use Arrays.from()
If you are dealing with NodeList
of DOM elements, you can get this issue.
1 2 3 4 5 6 7 8 |
const images = document.getElementsByTagName('img'); // ⛔️ Will throw TypeError: images.forEach is not a function images.forEach(element => { console.log(element); }); |
To resolve this issue, convert NodeList
to array using Array.from() and then use foreach on array.
1 2 3 4 5 6 7 8 |
const images = document.getElementsByTagName('img'); // Convert NodeList to array Arrays.from(images).forEach(element => { console.log(element); }); |
That’s all about how to resolve TypeError: foreach is not a function in JavaScript
.