Comparing for Loop with ES6 forEach Method
Before starting, let’s check what is for loop and what is forEach.

For Loop

For is a keyword, to create looping statements, just like while and do…while. JS engine can directly understand what it is.

forEach

forEach is a function defined in Array.prototype , just like all other functions. The engine can’t understand it directly. It needs to get the function definition in order to execute it.

For vs forEach

Choosing one over another will have huge impact on performance. When you have to deal with an array of bigger size, choosing the right one matters.

Let’s see an example below.

//create an array with 100K entries

arr = [];

for(var i = 0; i < 100000; i++){

arr.push(i);

} //for loop

console.time("For Loop");

console.groupCollapsed();

for( i=0; i< arr.length; i++ ){

console.log(arr[i]);

}

console.groupEnd();

console.timeEnd("For Loop"); //forEach

console.time("forEach");

console.groupCollapsed();

arr.forEach( x => console.log(x));

console.groupEnd();

console.timeEnd("forEach");

The above code will log 1–100K on the console along with the time it takes to execute the function. The result is given below (on a laptop with 6Gb Ram)

forEach took 6 more seconds to execute it. logging on console usually takes some time. So 50+ seconds are reasonable. Let’s see another example.

//initialize an array with 100K entries

arr = [], a = [], b = [];

for(var i = 0; i < 100000; i++){

arr.push(i);

} //for loop

console.time("For Loop");

console.groupCollapsed();

for( i=0; i< arr.length; i++ ){

a.push(arr[i]);

}

console.groupEnd();

console.timeEnd("For Loop"); //forEach

console.time("forEach");

console.groupCollapsed();

arr.forEach( x => b.push(x));

console.groupEnd();

console.timeEnd("forEach");

The above will simply copy an array of 100K entries to 2 other arrays. Instead of a=arr and b=arr , we push the entries one by one. The time taken is given below.

forEach took more than twice the time taken by for loop.

When you are dealing with a small array, you can choose forEach as it is much simpler to write and they don’t have much difference in performance.

Why do people fall for forEach?

forEach is easy to write. Call back functions are used. No index variable is required. callback functions can directly access values one by one. Little cleaner than for loop.

Things they forget when moving to forEach
['Sagar V']
['JavaScript', 'Programming', 'Web Development', 'Software Engineering', 'Software Development']