.map() vs .foreach() vs for()

Many times in your development life, you will find yourself needing to loop over a collection of data in order to process some value. This will inevitably lead you to discover a number of possible options available.

Your first thought may be to use the ol’ tried and true for loop. This can usually get the job done, but it’s usually not the cleanest, most maintainable option. There exists additional array methods in JavaScript you will find very useful to add to your arsenal, such as forEach(), map(), reduce(), filter(), etc. They are all useful in different scenarios, which I will cover in the future, but today we will be comparing Array.map() and Array.forEach().

Summary:
* forEach will execute the given function once per array element
* map will create a new array with the return value of a given function called with each value of the original array

For example, say you are given an array of numbers and need to create a new array with values doubling the original array.

Given:

var myArray = [3, 0, 2, 1];

Using a simple for loop, you would end up with something like this:

var doubleArray = [];
for (var i = 0; i < myArray.length; ++i) {
    doubleArray[i] = myArray[i] * 2;
}

A functional approach using Array.forEach:

var doubleArray = [];
myArray.forEach(function(val, i) {
    doubleArray[i] = val * 2;
})

Another functional approach with Array.map:

var doubleArray = myArray.map(function(val) {
    return val * 2;
})

As you can see, the return value of Array.map is yet another array, so no need to initialize a new array and set it inside the callback. This should lead to better variable scoping and less headaches debugging in the future. You also get to make use of method chaining.

For example, say you now want to sort the resulting array.

If you are using Array.forEach, you will need to define the array, set each index inside of the callback, and then perform a sort operation on that array.

var doubleArray = [];
myArray.forEach(function(val, i) {
    doubleArray[i] = val * 2;
})
doubleArray.sort();

Using Array.map, you simple return the values for each index in the callback, and then immediately run a sort() command on the return value:

var doubleArray = myArray.map(function(val) {
    return val * 2;
}).sort()

You can add any number of additional array method to the chain to perform multiple sequential operations.
I don’t plan to go into too much detail on method chaining in this post. In this example, I will passing callbacks to each method rather than using an anonymous method:

var doubleValues = function(value) {
    return value * 2;
}
var removeMultiplesOfThree = function(value) {
    return value % 3 !== 0;
}
var doubleArrayNoThrees = myArray.filter(removeMultiplesOfThree)
                                 .map(doubleValues)
                                 .sort();

Here you can see that we are first filtering out any multiples of three, doubling the remaining values, and then sorting those.

These are just a few quick examples to get you started using JavaScript’s Array.map(), which can hopefully lead you in to programming in a more functional style.

Getting Started…

So you finally did it. You’ve graduated college and became the big hot shot programmer that you always believed your dad wanted you to. You breeze through the training material and are handed your first real assignment.

Add some arbitrary change to this website

You think to yourself, “Hey I solved the bin packing problem all in C and created a compiler from scratch using only core Java libraries. This sounds easy enough”. So you dive right in.

Only until now you realize you didn’t learn how to do any of this in college. You were too busy being an academic and, therefore, better than all of your friends. So you hop on to your favorite search engine and quickly find yourself entering the most embarrassing search queries possible.

How could you, a solid 3.06 GPA student, struggle to find the simplest of answers in your infinite array of computer science knowledge? It can be humbling. It may be overwhelming. It willbe frustrating.

But don’t worry, many others have been exactly where you are and succeeded, and you will too. Others (myself included) find themselves searching the internet for a quick answer to an easy (read: stupid) question on a daily basis. And that’s how you ended up here. I won’t claim to know everything there is to know about development, but chances are I’ve ran in to a similar issue as you, and hopefully you can learn from me as much as I’ve learned from others.