A revolutionary and amazing new way to loop through arrays
The forEach loop behaves pretty much like your standard for loop, except that it’s a function that you call only on arrays. It looks like this:
The above code passes an anonymous function into the forEach method, but you can use any function you want. Within that function, element refers to the current element in the array, index is the index of the current element of the array, and array is the array the forEach function was called on (note: you don’t have to pass in all the variables; just make sure you pass them in in the correct order). The forEach loop is a pretty handy alternative to the standard for loop and something I’ll definitely be turning to in the future.
The only drawback is that the forEach loop is relatively new, so you’ll have to provide a fallback for older browsers if you’re worried about compatability. Mozilla’s documentation provides an extensive article on the forEach loop and elaborates on a method to provide that fallback for older browsers I was talking about earlier.