Fixing the “forEach is not a function” Error in JavaScript

What is the problem?

You see an error saying “forEach is not a function” when running your code.
This happens because:

  • You tried to use forEach on something that isn’t a list (like a single word or a group of items that aren’t in a list).
  • You might have typed foreach instead of forEach (JavaScript uses lowercase “e”).

How to fix it

Step 1: Check if it’s a list (array)

forEach only works with lists (arrays).
Example of a list:

const shoppingList = ["apples", "bread", "milk"];

Step 2: Use the correct spelling

Write forEach, not foreach.
Example:

shoppingList.forEach(function(item) {  
  console.log(item);  
});  

This will show each item in your list.

Step 3: Turn non-lists into lists

If your data isn’t a list, convert it first.
Example:

const notAList = "hello";  
const turnedIntoList = Array.from(notAList); // Makes ["h", "e", "l", "l", "o"]  
turnedIntoList.forEach(...);  

Tips to avoid mistakes

  1. Use tools like map, filter, or reduce for lists (they keep your original list safe).
  2. Check for errors in your browser’s developer tools (press F12 and look at the “Console” tab).

Need more help?

  1. Ask on free forums like FreeCodeCamp.
  2. Practice with small code examples.

I Can Fix Your Website Too!

If your WordPress website has errors (like Divi or Elementor issues):

  • I’ll fix bugs, broken pages, or layout problems.
  • Free website checkup: I’ll find hidden errors.

Contact me today!

Summary

  1. Use forEach only on lists.
  2. Spell it forEach, not foreach.
  3. Ask for help if stuck!

Let me know if you need more examples!

Written by Ethan Longhurst

20/04/2024

You May Also Like…

Receive your free quote!

Receive Your Free Audit!