DEV Community

Discussion on: My Top 3 JavaScript Array Methods

Collapse
 
nbeers22 profile image
Nate Beers

The reason why people would use a for loop over a foreach loop is for speed. For loops perform much faster than a foreach

Collapse
 
georgehanson profile image
George Hanson

Unless you are looping over massive arrays, it doesn't really matter in my opinion. I'd much value readability over a couple of milliseconds. If it proved to be a performance issue in the grand scheme of things it could always be replaced with a for loop.

Collapse
 
jamesthomson profile image
James Thomson

Agreed, I'll almost always opt for forEach. Though for allows you to break out early, which is nice when needed.

Thread Thread
 
berniwittmann profile image
Bernhard Wittmann • Edited

Actually this is also possible with forEach, since a function is called for each element. just do a return

EDIT: This was a misunderstanding of the desired behavior. Using return will just skip the current element and continue with the rest of the array, see my comment below

Thread Thread
 
jamesthomson profile image
James Thomson

You sure about that? AFAIK forEach will continue to run until the end of the array.

jsfiddle.net/jamesbrndwgn/mz0ynkvb/

Unless there's some trick I'm not aware of?

Thread Thread
 
berniwittmann profile image
Bernhard Wittmann • Edited

Ah I'm sorry I understood you wrong. I thought you meant skipping an element like continue. You meant completely stop after a certain element. This is currently not possible with forEach, but you could use for (obj of array) or some instead to achieve that behavior
Sorry again for the misunderstanding