Feb 20 2014

Fundamentals: An introduction to forEach, map and reduce.

Silhouette of streetlights against a white sky

Mastering these three methods on arrays will reduce the size of your code, improve its readability and let you show off your knowledge of functional programming.

The easiest way to jump into this is to provide you with an example of how you could accomplish a given task only using for loops, and then show you how you could improve your code.

task 1: loop over a set of names, logging them each to the console

var names = ["tom", "joe", "danny", "jim"];
for(var i = 0; i < names.length; ++i) {
console.log(names[i]);
}

This code will produce the desired output, but let's take a look at

forEach
and how it can help us for looping over an
array

names.forEach(function(value, index) {
console.log(value);
});

This revision is accomplishing the same goal but with less code – stepping over each element in the array without having to create a local variable to hold our current iteration index.

task 2: convert a list of names into just a list of initials

var initials = [];
var names = ["tom", "joe", "danny", "jim"];
for(var i = 0; i < names.length; ++i) {
// you can access the n`th char in a string via
// an array based index.
initials.push(names[i][0]);
}
return initials;

This is starting to seem pretty darn complex, for something that should be simple.

Well, let's take a look at how

map
is going to reduce our lines of code, and make this more readable.

return names.map(function(v){return v[0] }));

That is all it takes. No looping, no temporary array that we push into, just a function call.

task 3: convert a list of names into a single string

var list = "";
var names = ["tom", "joe", "danny", "jim"];
for(var i = 0; i < names.length; ++i) {
list += names[i];
}
return list;

Alright, a more contrived example for sure, but at a high level, the requirements are to reduce a list into a single value. In some ways

reduce
is similar to
map
, however we want a single value, not an array of elements.

return names.reduce(function(previous, value){
return previous+value;
});

It is good to keep these methods on the top of your head, so that when the opportunity arises, you can wield your functional sword into battle!

Sam Saccone @samccone

MojoTech

Share: