forEach, a way to manipulate arrays

The array method forEach( ) was introduced with ECMAScript 5 when nine new methods were added to help developers create ways of searching and manipulating array contents. These methods perform operations that previously would require complex iterative loops. The nine additional methods are: indexOf, lastIndexOf, every, some, forEach, map, filter, reduce, reduceRight. All these methods are variations of the forEach() method which I’m about to discuss.

forEach( ) performs a specified action for each element on the array. The specification of what to do is written by the programmer as a function in the form of an argument to the forEach() mechanism.

Remember, the purpose of a function is to store some code that will run when the function is called. We create the function, and forEach() will process it.

So, forEach( ) takes a function as its argument. The parameters of the function itself will interface with each valid element of the array in an iterative manner, just like a loop would do. By valid element I mean an element with data ( not an empty element location). Array indexes not having a value, or the value being undefined (if any), are ignored.
1- Let’s experiment with this method in increments. Start by introducing on the console a new array (I’m using Chrome):

var g = ["red", "blue", "white"];

2- Call forEach( ) on the array g by using a function with just one parameter, “y” , and in the function we stored a simple console.log output:

g.forEach(function(y) {

The function being used here may contain up to 3 arguments. The first argument (as the example above), points to the array data. In the forEach( ) example given above, the parameter y will point to the value of each index on the array, and the method forEach will process each value according to the instructions on the body. In this case the next instructions are to console.log each value at each “y” iteration and the result is: red blue white (in separate lines).

For a more detailed explanation as well as an explanation of all the other 8 methods please refer to my eBook:


Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s