forEach() method to exeucte a function on every element in an array.
Typically, when you want to execute a function on every element of an array, you use a for loop statement.
For example, the following code shows every element of an array to console:
forEach() method that allows you to run a function on every element.
The following code uses the
forEach() method that is equivalent to the code above:
forEach() method iterates over elements in an array and executes a predefined function once per element.
The following illustrates the syntax of the
forEach() method takes two arguments:
callback function that the
forEach() method uses to execute on every element.
The callback accepts the following arguments:
currentElement: is the current array element being processed.
index: the index of the
currentElementin the array.
array: the array that calls the
array are optional.
thisArg is a value to use as this when executing the callback.
Note that the
forEach() function returns
undefined therefore it is not chainable like other iterative methods:
One limitation of the
forEach() method in comparison with the
for loop is that you cannot use the break or continue statement to control the loop.
To terminate the loop in the
forEach() method, you must throw an exception inside the
forEach() method example
Let’s take a look at an example of the
forEach() method that uses a
The following illustrates
Counter constructor function:
This example shows how to pass the counter object to the
How it works.
- First, create a new
- Next, define an array of three numbers.
- Then, declare a variable
sumand assign it a value of zero.
- After that, call the
forEach()method on the
numbersarray. In the callback function, add the element to the
sumvariable and call the
increase()method of the
counterobject. Notice that the
counterobject is referred to as
thisinside the callback function.
- Finally, log the value of the sum and current value of the counter in the web console.
forEach() method to execute a callback on every element of an array.