DEV Community

Discussion on: Ditch For... Loops - How to Use ES6 Array Methods to Loop Over An Array

Collapse
uuykay profile image
William Kuang • Edited

For loops are actually much more flexible, and the JS parser is faster to interpret them in some benchmarks.

Let's look at a simple example where for loops beat array methods.

Say you have an array of numbers but some elements are null, e.g. [1, null, 3, null], now you want to transform this so you remove the nulls and multiply the numbers by 2.

With array methods you'd filter, then map. That's already 2 loops.

Just write 1 for loop that continues when it sees a null, and pushes 2*number into a new array.

Don't use the wrong tools for the job.

Collapse
mrothe570 profile image
Michael

This is what I was thinking. It isn't the point of the syntax to be cleaner or replace for... loops. It's to provide an alternative when appropriate. Just like you said use the right tool :)