forEach

Davemills
1 min readSep 20, 2021

What is forEach? When do you use forEach? How do you loop through an array?

The forEach() method calls a function once for each element in an array, in order without mutating or changing the original array.

The forEach method passes a callback function for each element of an array together with the current value (required), the index (optional), and the array (also optional).

Firstly, to loop through an array by using the forEach method, you need a callback function (or anonymous function). The function will be executed for every single element of the array. It must take at least one parameter which represents the elements of an array.

Consider the below array.

let numbers= [10, 20, 30, 40, 50];numbers.forEach((num) => {console.log(num * 2);});

The output of this array in the console log would be;

20
40,
60
80
100

However, the original array would remain intact, even though we iterated through the array. If you typed numbers to find the value assigned, you’d see it is equal to the original array.

numbers = [10, 20, 30, 40, 50]

Another example of this would be the following:

const a = ["a", "b", "c"];a.forEach((entry) => {console.log(entry);});

The output of this code is:

a
b
c

However, the original array of [“a”, “b”, “c”] is still the same and hasn’t mutated or changed.

This was a quick glance into the world of forEach(). When using forEach, the original array is not changed or

--

--

Davemills

I am studying software engineering at Flatiron. I plan to work with companies interested in a sustainable future.