JavaScript — Comparison between ‘for loop’ vs. ‘forEach’
for loop
for
loops are much more efficient. It is a looping construct specifically designed to iterate while a condition is true, at the same time offering a stepping mechanism (generally to increase the iterator). Example:
for (var i=0, n=arr.length; i < n; ++i ) {
...
}
This isn’t to suggest that for-loops will always be more efficient, just that JS engines and browsers have optimized them to be so. Over the years there have been compromises as to which looping construct is more efficient (for, while, reduce, reverse-while, etc) — different browsers and JS engines have their own implementations that offer different methodologies to produce the same results. As browsers further optimize to meet performance demands, theoretically [].forEach
could be implemented in such a way that it's faster or comparable to a for
.
Benefits:
- efficient
- early loop termination (honors
break
andcontinue
) - condition control (
i<n
can be anything and not bound to an array's size) - variable scoping (
var i
leavesi
available after the loop ends)
forEach
.forEach
are methods that primarily iterate over arrays (also over other enumerable, such as Map
and Set
objects). They are newer and provide code that is subjectively easier to read. Example:
[].forEach((val, index)=>{…