This tutorial demonstrates using the Array.forEach() method to loop through arrays with some examples.

forEach() is designed to run a function on each indexed element in an array. Starting at index[0] a function will get called on index[0], index[1], index[2], etc… forEach() will let you loop through an array in much the same way as a for loop.

Explore JavaScript Courses

Let’s take a look at some parameters passed into the forEach() callback function. These parameters include the current value, array index, and also the array itself.

These parameters helpful when traversing an array to perform some task on each array index value.

this_context is an optional parameter to set scope, and a more in depth explanation can be found at the following Array.prototype.forEach() MDN article

forEach is great for looping over an array of values to run a function on each value. Also, forEach() is a good alternative to using a for() loop. forEach let’s us reuse a callback function for readability. The below example compares the readability of a for loop versus using the forEach() method.

Let’s start with an example using forEach() to loop through an array of numbers. This example checks if each number in the javascript array is even or odd.

The following example uses the forEach() array method to separate even numbers from odd numbers into two separate arrays.

What if we had a couple of shopping carts of items? Say you wanted to total the cost of your shopping cart. The following example totals the cost of all items from our shopping carts using the forEach() method.

For more examples of looping through or iterating over javascript arrays or objects checkout this 2ality post on Iterating over arrays and objects.

Explore JavaScript Courses

While the forEach() method can be useful, forEach() does come with some disadvantages. Maybe you are wondering how to break out of a forEach() loop early. One of the negative issues with using forEach() is that there is no way to terminate or break out of the loop without throwing an exception. Since a forEach() returns a value of undefined, forEach() is not chainable like map(), filter(), or reduce().

forEach is great for looping through an array to execute a function on each of those values. forEach() is also a nice alternative to using a for() loop for code reuse and readability.

The following two tabs change content below.

DJ Rosenbaum

Independent Author and Coder.