forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm.
C# foreach loop is used to iterate through items in collections (Lists, Arrays etc.). When you have a list of items, instead of using a for loop and iterate over the list using its index, you can directly access each element in the list using a foreach loop.
Even though using return inside the callback of a forEach() loop would halt execution for the current iteration and move on to the next item in the loop, you should not use it to mimic the functionality of continue .
Correctly used, while is the fastest, as it can have only one check for every iteration, comparing one $i with another $max variable, and no additional calls before loop (except setting $max) or during loop (except $i++; which is inherently done in any loop statement).
I recommend to always use for … of
in ES6.
continue
, break
, return
, yield
and await
.Also I personally find it more readable, but that comes down to preference. Some people think forEach
is a more functional style, but that's wrong - it has no result value and is all about doing side effects, so an imperative-looking loop fits that purpose better.
Performance is not a concern, in modern engines all loop styles are equivalent.
This is a very intersting question which has been discussed in many other sites. I'll post the basics of what I have read.
ForEach exclusively belong to the royal family of Arrays. The forEach method was introduced with lineage to the prototypal inheritance of Array object! Needless to say, the forEach clause works only with those data structure which are Arrays. The method basically iterates over the elements of the array and executes a callback function [basically some executable function/ fun activity].
The for-of loop is adequately new to the JS world and packs in super-powers! Voilaaaaaaa! The for-of loop creates a loop iterating over iterable member objects. The list is an extensive one such as
You need to know that this bad-ass boy emerged with the birth of ES6 in 2015. So, it offers plenty of flexibility in usage
Performance
In performance, for...of
is faster than forEach
. Results can be found here
forEach
is 24% slower than for...of
There are several other iterable classes in the W3C specification, like FileList, as I mentioned above. And in recent drafts of W3C (around when ES6 was released), collections like HTMLCollection and NodeList now implement forEach() as well, not just Array anymore. By @Patrick Roberts
Source Links:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With