Ire Aderinokun has written a nifty piece using loops and when we might consider replacing it with another method, say
.filter(). I particularly like what she has to say here:
As I mentioned earlier, loops are a great tool for a lot of cases, and the existence of these new methods doesn't mean that loops shouldn't be used at all.
I think these methods are great because they provide code that is in a way self-documenting. When we use the filter() method instead of a for loop, it is easier to understand at first glance what the purpose of the logic is.
However, these methods have very specific use cases and may be overkill if their full value isn't being used. An example of this is the map() method, which can technically be used to replace almost any arbitrary loop. If in our first example, we only wanted to modify the original articles array and not create a new, modified, amazingArticles, using this method would be unnecessary. It's important to use the method that suits each scenario, to make sure that we aren't over- or under-performing.
If you’re interested in digging more into this subject, Adan Giese wrote a great post about the
.filter() method a short while ago that’s definitely worth checking out. Oh, and speaking of lots of different ways to approach loops, Chris compiled a list of options for looping over
querySelectorAll NodeLists where
forEach is just one of many options.