for (var i = 0; i < array.length; i++) {
}
- Code has to run in old versions of IE.
- Code is extremely hot: like, code that runs for tens of thousands of iterations.
- When you want to use old-fashioned control statements like
break
orcontinue
orgoto
to control your flow
var result = array.map(function(item) { });
- When you are mapping one kind of things to another kind of thing. The
.map
iterator is all about the fact that what you return from the function gets added to an array, and you should want that. Otherwise you're creating a big new array for no reason that's just filled withundefined
.
var result = array.map(function(memo, item) { });
- When you are mapping a list of things into one thing. For instance, taking a sum or a count or some kind of aggregate figure based on a big list of things.
array.forEach(function(item) { });
- When you aren't mapping things to another kind of thing, or reducing things to one thing, but doing something else.
- When you want a scope per iteration: for instance, if you're doing async things and want your variables to not change values every iteration.
.map
and .reduce
are functions that make it easier to transform data. You can use them as general-purpose "I want a loop" functions but it's not semantic and can be wasteful: if you just need a loop, use .forEach
or for
.
FAQ:
- why use for loops for hot code? Well, functional iterators need to create and dispose of a variable scope every time they run. This makes them slightly slower.
Why does this miss out
for ... in
andfor ... of
?-1