This is a very interesting 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
- Array
- Map
- Set
- String
- TypedArray
- Other W3C classes
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
Update
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: