TypeError: foreach is not a function in JavaScript

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.

You will get following error when you execute the program:

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.

Output:

If you are just interested in values, you can use Object.values().

Output:

If you need both key and value in an array, then you can use Object.entries().

Output:

Use Arrays.from()

If you are dealing with NodeList of DOM elements, you can get this issue.

To resolve this issue, convert NodeList to array using Array.from() and then use foreach on array.

That’s all about how to resolve TypeError: foreach is not a function in JavaScript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *