JavaScript forEach - Powered Array for loop

Know the ins and outs of this basic JavaScript array function

Feature Image

As one of the basic control structures in programming, loops are almost an everyday addition to the code we write. The classic for loop is one of the first code snippets we learn to write as programmers.

If you were a Javascript developer, you would know that Javascript is no stranger to iterating through the items of an array or a map using classic for loops. But did you know that Javascript has a much cleaner and safer method for the same task other than the simple for loop? It’s the Javascript forEach method.

Unlike the simple for loop, where we use the array indices to access its items, the forEach method executes a passed callback function on each item in the array without manually retrieving each item. As a feature introduced under ES5, it is now supported by all the major browser versions and Node.js 10.0 upwards.

Given its importance, we decided to explore further into Javascript forEach method and see when and where to use it and understand how it works under the hood.

Without waiting any longer than, let’s start our exploration.


Javascript forEach vs. for loops

We all are familiar with how to iterate through an array using a for loop.

let array = [1, 2, 3, 4]

for (let i=0; i < array.length; i++) {
    console.log(i);
}

In comparison, a forEach loop looks like this:

let array = [1, 2, 3, 4]

array.forEach(num => console.log(num))

We can see that forEach method, instead of retrieving each item using its index, passes each array item as an argument of the callback function. The callback executes on every array item, one after the other.

When we compare these two looping methods through an array, the forEach method is cleaner and easier to implement since we don’t have to manually set array index limits like in a for loop.

Not manually setting index limits and not directly accessing array items using indices also make forEach method less prone to developer mistakes and unnecessary bugs. So we can say the use of forEach is much safer.

A forEach method runs in its own scope. So you won’t have to worry about its code clashing with or unnecessarily changing the variables in the outer scope. On the other hand, for loops belong to the same scope as the code it is placed in.


Javascript array forEach method parameters

In the previous example, you saw how the forEach method works. Now let’s see the actual parameters accepted by it.

arr.forEach(callback(currentValue[, index[, array]]) {
  // execute something
}[, thisArg]);

As you can see, the forEach method accepts a callback function that defines how to process each array item accessed while iterating through the array. In addition, it accepts another parameter named thisArg. If passed, thisArg value will be used as the callback’s this value. If not, the callback function’s this value will be determined by the rules indicated in this MDN .

The callback function has one required parameter, currentValue, and two optional parameters, index and array.

  • currentValue: Array item currently being processed in the loop.
  • index: index of the currentValue array item
  • array: array on which the forEach method was called upon

Here is an example of a forEach method that makes use of these parameters.

function Processor(){
    this.max = 0;
    this.maxAt = 0;
}

Processor.prototype.findMax = function(array){

    array.forEach((num, index) => {
        if (num > this.max){
            this.max = num;
            this.maxAt = index;
        }
    }, this)
}

const processor = new Processor();
processor.findMax([23, 12, 1039, 139, 2311])

console.log(processor.max)  //2311
console.log(processor.maxAt)  //4

Javascript forEach method—range of iteration

In forEach, the range of the visited items is set before the callback function’s first call. Once it starts iterating over an array, any new items you add to the array won’t be visited by the callback.

Therefore, if we run the following code snippet,

let array = [1, 2, 3, 4]

array.forEach(num => {
    array.push(num+4)
    console.log(num)
})

It will give the following output.

1
2
3
4

But at the end of the forEach method’s execution, the array contains numbers up to 8.

[1, 2, 3, 4, 5, 6, 7, 8]

When to use forEach method

Any problem that requires looping through an array is a good place to use the forEach method. If none of the other task-specific array methods like map, filter, or reduce applies to your problem, use the forEach method instead of the classic for loop.


When not to use forEach method

One use case where a for loop should be used instead of a forEach loop is when you want to break early from the loop.

For example, consider the following scenario.

let array = [23, 1, 122, 121, 87]

for (let i = 0; i < array.length; i++){
    if (array[i]%2 == 0){
        console.log("Found an even number: " + array[i])
        break;
    }
}

forEach method doesn’t provide a mechanism to break early from the loop like the above for loop does.


Building our own forEach method

Building our own forEach method will help us understand how the forEach method works under the hood better. Here I have the code for a simple implementation of the forEach method. Remember that this is not exactly how the forEach method is implemented in standard Javascript; we are using this code only to conceptualize and understand how forEach method works beyond the surface level.

Array.prototype.forEachConceptual = function(callback, thisArg) {
    if (!this) {
        throw Error('Array.prototype.forEach called on null or undefined');
    }

    if (!callback || typeof callback !== 'function') {
        throw Error('callback is not a function');
    }

    for(i=0;i<this.length;i++) {
        callback(this[i], i, this);
    }
}

In this implementation, first we go through the basic type checks for this instance and callback function. Then, we use a for loop to iterate through the items in the array and call the callback function on each of them.

Although we have directly prototyped this method to Javascript’s standard array type, this is only for conceptualizing purposes. You should never prototype methods into Javascript standard types in your production code.


Summary

Today we discussed how the forEach method in Javascript works, why it’s different from the standard for loop, and when you should and shouldn’t use the method in your code. In the end, we built a simple forEach method to understand how it works under the hood.

As one of the most useful Javascript array methods, I hope this post will help you use the forEach method optimally in the future. If you want to learn more on Javascript array methods, check out our post on 15 must-know Javascript array methods next.

Join more than a thousand developers!

Subscribe now to our free, weekly e-mail with the best new articles, courses, and special bonuses.

We won't send you spam. Unsubscribe at any time.