Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Forked from tmcw/iteration.md
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/c55f235b36113247f790 to your computer and use it in GitHub Desktop.
Save joyrexus/c55f235b36113247f790 to your computer and use it in GitHub Desktop.
javascript iteration options

What kind of iteration to use when in JavaScript?

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 or continue or goto 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 with undefined.
var result = array.reduce(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.

TL;DR

.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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment