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)
I personally use
forEachloops wherever possible. The only time I will need to use aforloop 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).for ofloops 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 inon 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.
forEachis also used to loop over arrays but takes a function instead.The advantage of
for ofwould be that you can use keywords likebreakandcontinueto alter the flow which is not possible withforEach.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: