A revolutionary and amazing new way to loop through arrays

…well, revolutionary and amazing to me, anyhow. Like most Javascript programmers, I usually use a for loop to iterate through my arrays, a method which typically works pretty nicely and doesn’t really have many drawbacks. However, I recently discovered another method which takes a tad less typing while maintaining the same functionality–the forEach loop. It’s quite handy and you don’t have to declare a bunch of variables to loop through an array.

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:

myArray.forEach(function(element, index, array) {
console.log(element); // element is the current element in the array
console.log(index); // index is the position of that element in the array
console.log(array); // this is the array the forEach loop was called on

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.

Leave a Reply

Your email address will not be published. Required fields are marked *