JavaScript Array forEach()

Lorgio Roda Roca
3 min readNov 29, 2021

Hi there,

I think we have all had trouble understanding array methods. Because of this, I have decided to write some posts going through these methods. This will be a guide, the guide I would have liked to have when I started programming, explaining the array methods I use the most in my current job as a junior programmer.

So let’s start with forEach.

So the question is:

What is forEach?

ForEach is a method that executes a function once for each element in an array. Let’s use it to sum an array of numbers.

In the next example, we want to build a list of dog names. We use a for loop to add each name to an array. That requires looking elements up by their indexes ‘i’.

forEach lets us write the same code without the index variable ‘i. We pass a function to forEach, which runs the function on each element.

With this example, a for and forEach have the same result, but a functionality difference because a forEach passed a callback function for each element of an array.

Also, we can modify the array’s elements during the forEach:

The callback function can reference, and even modify, variables defined in outer scopes. In the next example, the callback function modifies the result variable.

The second argument to forEach’s callback is the item’s index.

The examples above defined the callback function inline, at the point where we called forEach. Functions are values in JavaScript, so we can pass them in other ways as well. For example, we can put the function in a variable, then pass the variable to forEach. The following examples define our forEach callback function in different ways, but they all have the same effect.

Why is forEach used?
The forEach loop is used to iterate over the elements of a collection, which may be an array or a list. It executes for each element present in the array. In the loop body, you can use the loop variable you created rather than using an indexed array element.

Also in this link here, you have 2 exercises for reinforcing what was learned.

In the next post, I will talk about the map method, don’t miss it.

If this explanation was good for you, or you want to add something, type me in the comments.

--

--

Lorgio Roda Roca

Hi there! I am Lorgio Roda. An enthusiast programmer. Web Developer with React.js and Node.js as my tech stack.