Posts Is forEach a loop in JavaScript?
Post
Cancel

Is forEach a loop in JavaScript?

This question has confused many of us for a long time, is it a loop? or is it a function?

In JavaScript a for loop repeats until a specified condition evaluates to false, it is similar to the Java and C for loop, let’s assume there’s an array of students and I want to print information of each student.

I can use a for loop to print all the students inside an array.

1
2
3
for(var i=0; i<students.length; i++){
    print(students[i]);
}

In above code snippet I have created a counter variable i and I am using it to track each iteration and student associated with it, but it doesn’t look quite readable. can we do any better? forEach is here!

What is forEach?

forEach is a function available on Array class which can be used to iterate over an Array instance.

Let’s re-write the above code snippet using forEach syntax.

1
2
3
students.forEach(function(student){
    print(student);
});

This code snippet describes what it does, It almost looks like a sentence.

Conclusion

In JavaScript forEach is not a loop, it is a higher order function available on Array class which triggers the provided callback with each element inside an array in sequential order.

Polyfill

1
2
3
4
5
6
7
8
9
if(window.Array && !Array.prototype.forEach){
    Array.prototype.forEach = function(cb, thisArgs){
        var items = this;
        thisArg = thisArg || window;
        for(var i=0; i<items.length; i++){
            cb.call(thisArgs, items[i], i, items);
        }
    }
}

Specifications

ECMAScript (ECMA-262)
The definition of ‘Array.prototype.forEach’ in that specification.

Updated Apr 10, 2020 2020-04-09T20:54:17+00:00
This post is licensed under CC BY 4.0