Dear JavaScript Aficionado,

The error with the message “forEach is not a function” is a nasty one that has an easy explanation but can be challenging to debug.

Basically, the problem is that the variable or the constant on which you seek to invoke the method “forEach” isn’t an array. And because only objects that are arrays have this method, you get an error.

The naive solution is to check whether the variable is an array and if it’s not, then skip calling forEach. It could be something like this:

const data = ["apple", "orange", "grape"];

//Preferred way to check whether it's array 
if (Array.isArray(data)) {
    data.forEach(el => console.log(el));
}

//Not-so-preferred way
if (data instanceof Array) {
    data.forEach(el => console.log(el));
}

Note: Why “Array.isArray()” and not “instanceof”? Read: developer.mozilla.org

But that’s only sometimes the proper way to handle the bug…

You first need an answer to the question:

Why it’s not an array in the first place?

If the variable or the constant in question is always meant to be an array, then you must find out why it is not in this specific case.

There are many possibilities:

  • There can be another bug earlier in the code;
  • There can be wrong, not validated data;
  • There can be a new data format that wasn’t considered initially;
  • It may be that the variable or the constant isn’t meant to be an array at all;
  • It can be the wrong variable or constant;
  • It can be a misspelled variable or a constant name;
  • It can be a “variable scope” issue;

Perhaps those are the most common reasons why the code throws “forEach Is Not A Function.”

Some of those possibilities are super easy to be fixed, and others, like the appearance of a new data format, will lead to more substantial changes in the “business logic.” 

Hence, you need to know why you make the change and how exactly it should handle the new case.

Be Happy,

Sashe

P.S. If you would like to read about more advanced tips, techniques, and strategies, check out this link (I think you’ll like what’s on the other side)