DEV Community

Discussion on: I Use For Loops Almost Always In Javascript

Collapse
 
mooshallski profile image
mooshallski

This topic has been worked so many times. I don't know what Kent did. Maybe he itereated over the array first to filter and then did iteration for reduce and in terms of for loo only one iteration was done. Don't know. But the truth is that in case of loop you should almost always use filter/map/reduce. First of all it's always better to have a declarative code. It produces less confusion, which as Kyle Simpson says - is a reason of most bugs. I'm not talking about one-liners vs couple line of code. Experienced programmer should know that it's not the amount of code that counts. First of all obviously the name of this array methods makes you closer to quick understand what youre about to see. You look at the code and it's a matter of second when you notice: OK, so we have some mapped data, filtered one, reduced to one value etc, whereas with for loops you know absolutely nothing about those iterations until you work them through line by line. You can't really know the outcome, purpose, anything. Secondly it requires some of the good practises of programming when using map/filter/reduce. It's rare to see some bloated code within this methods. If one sees that during code review than it's clear that someone made it wrong. In for loops there are so many place where you can make sth wrong, where somebody may overlook what you wanted to do. There is no really required structure, it probably won't be pure. When it comes to breaking the loops, you can also do that without for. Just simply use Array.prototype.every. It will do pretty much same thing.