# map vs. for loop

## So why use map?

One of the most difficult questions I get when teaching is why we use constructs such as .map over for loops. I don’t think that I have a great answer. Even searching online for “for loop vs. map” and the like, I can’t find anything really concrete. It is interesting to me that all the top results I find for this search are related to JavaScript even though this could certainly apply to other programming languages that have a map and similar constructs as well. It also seems to be pretty contentious to some people.

## What are Arrays?

I always keep my wife in mind when I write these articles. She is not a programmer, but I think she has an ancillary understanding of programming concepts what with being forced to live with me. Thus, I’ll start with the basics even though most developers and even many laypeople will already understand this.

names = ['andrew', 'james', 'crites']
capitalize(names[0])
capitalize(names[1])
capitalize(names[2])
x = 1
print names[x] // 'james'

## How the for loop works

Arrays can be of arbitrary length. All of the array examples above have three items in there. They have a length of 3. However, arrays can be of essentially any size from 0 (empty) to millions of items or more. For example, if we have an array of a person’s names such as ['andrew', 'james', 'crites'] it’s certainly plausible that they would have two, four, or some other number of names like ['santiago', 'juan', 'mendez', 'menendez'] or ['john', 'smith'].

x = 0;
for x < names.length:
capitalize(names[x])
x = x + 1
• For x starting at 0…
• As long as x is less than the length of the names array…
• Capitalize the xth element of the names array…
• Then add one to x

## True Iteration with map

Some languages allow you to perform true iteration using the for keyword, such as for (element: array). This will make element each element of the array in order inside of the for loop block. I won’t discuss this iteration construct in this article — it’s more like forEach I mention later. Languages may also call map something else or have some other way of writing it.

names.map(name => capitalize(name))
capitalize(names[0])
capitalize(names[1])
capitalize(names[2])
capitalizedNames = names.map(capitalize)
capitalizedNames = []
for x = 0; x < names.length; x++
capitalizedNames[x] = capitalize(names[x]))

## Benefits of map over for loops

This is a list of the benefits of using map as I see them:

• True iteration — you know that your code is going to run on each element of the array in the right order.
• Immutability — if written properly, your original array will be unaffected. This has potential benefits in cases where the original array is still needed elsewhere. for loops can of course also be written so as not to update the original array, but it requires more code and updating our new array as part of our loop operation. map keeps this cleaner since you only have to work in one scope to still maintain immutability:
• Scope isolation and Reusability — often the function inside map only needs to work within its own scope, i.e. against the elements inside the array themselves. It doesn’t require any variables outside of its scope. A for loop may require this (such as declaring capitalizeNames outside the loop and also using it in the loop). This reduces the chances of making a mistake by updating something inappropriately in the wrong scope. This also makes it easier to extract the operation we use in map for clarity / isolation / reuse.
• Cleaner code — I think less code is strictly better as long as the original meaning isn’t lost. When doing identical things, map can almost always be written with less code than for. It can be cleanly written on one line sometimes whereas for requires at least two — generally three with braces included. Finally, the array element you are working with for map automatically gets a name. You would have to assign this to a variable when using for if you wanted it. name is clearer than names[x]. Scope isolation and a reduction in the amount of variables you need alongside reduced size all make code objectively cleaner. It’s arguable whether the meaning of map vs. for is lost on some people, but I think the next point helps:
• Specificity — this applies to iteration operators generally rather than just map. Each has a specific purpose. map calls a function for each element of the array and returns a new array. reduce calls a function for each element of the array and keeps the results in an accumulator whose ultimate value is returned. filter takes an array and returns a new array whose values have met some condition against the original array. Each operator has a specific purpose that is easier to reason about. for loops can be used more generally, and you have to inspect the code to determine how it’s being used in a specific case.
• Composability — it is much easier to compose iteration operations together. For example, you could do map(map(map)) (not that you should need to), or more realistically reduce(filter(map)) . If you wanted to do something similar for for loops, you would have to manage a separate array and iteration process for all three operations and their results.
strings
.map(toNumber)
.filter(isEven)
.reduce((sum, number) => sum + number)
numbers = []
for (x = 0; x < strings.length; x++)
numbers[x] = toNumber(strings[x])
evenNumbers = []
for (y = 0; y < numbers.length; y++)
i = 0
if (isEven(numbers[y]))
evenNumbers[i] = numbers[y]
// you wouldn't need i here if you used `.push` of course
i++
sum = 0
for (z = 0; z < evenNumbers.length; z++)
sum = sum + evenNumbers[z]

## Benefits (?) of the for loop

The for loop has potential benefits, but I don’t think they are as concrete as those offered by map or other iteration operators.

• Performance — maybe… I ran some unscientific performance tests of for vs. map on 10,000,000-item arrays in Chrome and Safari. map performed strictly worse in Chrome, but better in Safari. However, overall everything completed in 1–3 seconds which I think is still relatively fast for such a massive array. It’s plausible that you will work with such large arrays if you are doing things like processing video contents in-browser. Under these specific circumstances, if you need the benefit of around half a second of performance per-10,000,000 elements in Chrome you might be better off using a for loop for now. However, on other platforms / environments or other circumstances, map might still be faster, and in fact it may be faster in the future. Consider the other benefits of map and do your own testing before choosing for loops purely for performance reasons. Also keep in mind that while a for loop may run faster it might use more memory too.
• Familiarity — newer developers might not even know what map is, and it can be difficult to grasp at first. I think this is still a non-benefit, though, since it’s important for developers to always learn new concepts and see the benefits and drawbacks of each. I would also recommend that map be taught alongside and perhaps even instead of for nowadays. Perhaps there is some benefit to developers who use for being able to jump into a new code base without unfamiliar constructs, but I don’t think map is that difficult to understand… especially not compared to a lot of the other constructs or libraries you would expect a new developer to have to learn when transitioning platforms and languages. The benefits of familiarity in programming are not to be understated, but I think the solution here is to start teaching map earlier instead. In fact, some programming languages such as Rust don’t even have traditional for loops.
• Ease of understanding… but probably not — I think that the for loop is so ubiquitous and taught so early on that programmers have a grasp on it for most of their programming lives. This creates a possible illusion that it’s easier to understand. In fact, I think that map specifically may be easier to understand than a for loop in general. for loops for a specific purpose might be easier to understand, but since they can work so generally their meaning is not always clear. I think that map's specific purpose makes it clearer. I do wonder if we taught map first and then talked about for loops to someone who was brand new to programming whether they would find one or the other easier. Regardless, I don’t think that map is a difficult concept to grasp — not more than for anyway. It’s just that for gets hammered home so much. Also, once you understand map it’s easier to understand all of the other iteration operators available. All-in-all, this one is subjective.

## Non-benefits of map

I often hear the fact that map is “functional programming” as a reason why it’s beneficial. First of all, I can’t say I strictly know what functional programming means. I think it has a meaning similar “object-oriented programming” only its buzzword trap is worse. It seems like if you’re using map or the like in your code you’re doing functional programming in the same way that if you use objects in your code you’re doing object-oriented programming.

In JavaScript there is an array operator forEach which does the same thing as map except it doesn’t return a new array. I think that forEach is almost like a transition between using for loops and other operators. For example, you could write the even number sum code using forEach instead, and it might look like this:

numbers = []
strings.forEach((string, x) => numbers[x] = toNumber(string))
evenNumbers = []
i = 0
numbers.forEach(number => {
if (isEven(number))
evenNumbers[i] = number
i++
})
sum = 0
evenNumbers.forEach(number => sum = sum + number)

## In Conclusion

I hope that this helps answer the question about “why use map over a for loop” to some degree. I think that iteration operators such as map have concrete benefits that the for loop simply doesn’t have. I think that the benefits of the for loop relegate it to specific use-cases related to performance. I ask any infuriated for loop fanatic to think: if you had learned about and were using map consistently first, would you still like for loops better once you learned about them? Another way to phrase the question is: can you think of concrete benefits to the for loop besides familiarity? Imagine that any new developer you work with knows map as well … or maybe even instead of for. Can you list other benefits?

--

--

## More from Andrew Crites

Web developer and such

Love podcasts or audiobooks? Learn on the go with our new app.