I've been going over a few array methods to refresh some of them and this is one thing I've never fully grasped. There are for of loops and for in what is the use case for these?
In addition, you also have forEach what are the key differences? Is it performance or personal preference? I don't really understand the difference between them could someone point me in the right direction?
Top comments (3)
for of
loops are used for data structures that can be iterated over (iterables). Arrays and strings are examples of such structures. So if I have something like this:Would give me all the elements in that array.
for in
on the other hand is used for objects, where I want to loop over an object literal.Will list out the keys and corresponding values of the given object.
forEach
is also used to loop over arrays but takes a function instead.The advantage of
for of
would be that you can use keywords likebreak
andcontinue
to alter the flow which is not possible withforEach
.I personally use
forEach
loops wherever possible. The only time I will need to use afor
loop will be if I need to break out of a loop early (e.g. I'm looping through until I find a specific element, and then stopping).The for and for/in looping constructs give you access to the index in the array, not the actual element.
With forEach() and for/of, you get access to the array element itself.
Note: