DEV Community

gunderodd
gunderodd

Posted on

Mini Solutions Series #3: Can't forEach()

BUG:

"forEach() error" or "forEach() not working" or "for each is not a function javascript"

fail

Detailed Description:

In the past I haven't had enough confidence in my grasp on basic JS syntax to know why my use of the handy forEach() method wasn't working. I did complete Wes Bos's 30 Day JavaScript Series, and I vaguely remembered him mentioning something about a common beginner's mistake.

Fortunately, by this point in my studies there is less mystery about proper syntax, and I decided to pop into Stack Overflow, and it didn't take long for me to realize...

Solution:

...that what I was trying to iterate over LOOKED like an array, but it wasn't. It was an HTMLCollection. But you can turn that into an array with the equally convenient spread operator, and then use forEach().

The explanation that helped me.

Takeaway:

So, using

const myArray = [...document.getElementsByClassName('myClass')]

INSTEAD of

const myArray = document.getElementsByClassName('myClass')

BEFORE trying forEach() is the code that fixed my problem.

Bonus Tip:

I'm trying to cram a 4-6 month Udacity Fullstack nanodegree program into 1 free month. Saving money is a great kick-in-the-ass motivator, and I've never spent so many hours coding in a week. I can see that up until now I've underestimated my ability to soak in a lot of new information and debug dozens of new problems - my head is spinning a bit, but instead of feeling overwhelmed I actually feel more competent as a coder than ever before.

Top comments (0)