Javascript: forEach Is Not A Function and What To Do?

Table of contents

No heading

No headings in the article.

What is Loop?

A loop is a programming instruction that will cause a computer program to execute the same set of instructions over and over again as long as a particular condition is true.

The Traditional Loops

The traditional loops in functional programming are for and while loops. These loops are used to execute a series of statements or instructions repeatedly. The for loop executes a set of statements until a certain condition is met, whereas the while loop executes a set of statements as long as the condition is true.

Javascript forEach loop

The forEach method is an ES6 javascript iteration addition that executes code in arrow function for each item in an array. It can be used to iterate through arrays of any type and size, Map or Set.

It's different than the traditional "for loop". forEach passes a callback function for each element of an array with the following parameters: Current Value (required) - The index of the current array.

const techBlog = ['Nerd', 'Level', 'Tech']
techBlog.forEach((item, index)=>{
console.log(index, item)
// Output
// =====

// 0 Nerd // 1 Level // 2 Tech

Common Error Related - forEach:

We will generate that uncaught typeerror “forEach is not a function.", if we use the forEach like in the example below:

const nums = {
  "number 1" :1,
  "number 2": 2,
  "number 3": 3,
  "number 4":4

nums.forEach((num) => { console.log(num); });

// Output the error below image.

In that use case of the above example, we can use forEach with objects but not directly. To simple fix that we can use it with the built in keys object as it returns an array of keys or any array-like object, which is in these cases can be directly attached to forEach.

const nums = {
  "number 1" :1,
  "number 2": 2,
  "number 3": 3,
  "number 4":4

Object.keys(nums).forEach(key => { console.log(key +" : "+ nums[key]); });

// OR

Object.entries(nums).forEach(([key, value]) => { console.log(key+" - "+value); });

Wrapping up - Most Common Cause:

a- Calling "forEach" on a value that is not of type array, Map, or Set will result in the error “forEach is not a function." To fix this, make sure it's being used on an Array, Map or Set instead

b- You can also console.log the object and verify that it's an object of type Array, Map, or Set. If the type of Object is Object it needs first to be converted to these allowed types “Array, Map or Set“ then attach the forEach to it.

c- If it's fetched from a remote server, make sure you've parsed the JSON object to a native JavaScript array first.

Did you find this article valuable?

Support Ahmed Radwan by becoming a sponsor. Any amount is appreciated!