Iterating over the elements of the array in JavaScript is a very common task. In this tutorial you’ll
learn how to use the built-in array function forEach
to go over all array elements.
Before I tell you about forEach
, let’s recall how you can loop through an array
with the regular for
loop.
Imagine that you need to display the value of all elements of an array, each on a new line.
const arr = [ -1, 2, 4, 0, -5, 7 ];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Using a regular for
loop, you call the console.log
function on each iteration of the loop and pass the current
array element arr[i]
in it.
The forEach
function will allow you to shorten your code a bit. It is similar to the filter
function in a way as
you’ll also need a handler function to use it. This function will be called for each element of the array.
The fundamental difference is that forEach
does not return anything.
const arr = [ -1, 2, 4, 0, -5, 7 ];
arr.forEach(item => console.log(item));
Now let’s think about what we could make the example above even shorter.
The item => console.log(item)
function does nothing with the item
parameter other than passing
it further into console.log
which outputs item
to the screen.
It turns out that we could use the console.log
function without this wrapper from item => ...
and the result
would remain the same.
const arr = [ -1, 2, 4, 0, -5, 7 ];
arr.forEach(console.log);
Note that we don’t put parentheses after console.log
because we don’t call the console.log
function.
We pass it as a parameter to the forEach
loop, where it will be applied to each element of the array.
The call will be controlled by forEach
, not by us.
This is a very important point at which many interns stumble.