Skip to content

Instantly share code, notes, and snippets.

@tmcw
Last active June 20, 2021 08:51
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tmcw/1c7dd591b11f0fa55cdc to your computer and use it in GitHub Desktop.
Save tmcw/1c7dd591b11f0fa55cdc to your computer and use it in GitHub Desktop.

What kind of iteration to use when in JavaScript

For loops

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

.map

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.

.reduce

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.

forEach

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.
@lloydjatkinson
Copy link

lloydjatkinson commented Apr 8, 2018

Why does this miss out for ... in and for ... of?

-1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment