Skip to content Skip to sidebar Skip to footer

When/why To Use Map/reduce Over For Loops

So I am getting into a bit of object manipulation in JavaScript for the first time and I have a question I'm wondering if anyone could answer. When I have an object I want to manip

Solution 1:

I know I'm replying to an old answer but just wanted to point out for future readers.

Map reduce and filter functions come from the functional programming world.

These are first class built-in operators in languages like Lisp, Haskell, and others(ml?). Functional languages tend to prefer to run operators over immutable data than make the code run over the data to operate on it (say loops). So they provide simpler but powerful interfaces like map, filter and reduce when compared to providing for and while loops.

It also helps them satisfy other requirements like immutability etc. That's why maps give u back a new map instead of mutating the old one. These are very good from a concurrency point of view, though they may be slower in certain contexts.

This approach usually leads to fewer errors in code in multi-threaded or high concurrency apps. When multiple actors act on the same piece of data, immutability helps keep code from stepping on each other's toes.

Since javascript tries to be partially functional by providing some functionalities of functional programming languages, it might have made sense to implement map, filter and reduce functions in it too.

YMMV depending on what you are doing with the tools you are given.

If your code works better with a for loop, go for it.

But if you ever find asynchronous code munching on common data and you end up splitting your hairs trying to debug a loop. Say hi, to map, reduce and filter.

Solution 2:

.map() allows you to create a new array by iterating over the original array and allowing you to run some sort of custom conversion function. The output from .map() is a new array.

var orig = [1,2,3,4,5];
var squares = orig.map(function(val) {
    returnval * val;
});
console.log(squares);   // [1,4,9,16,25]

.reduce() allows you to iterate over an array accumulating a single result or object.

var orig = [1,2,3,4,5];
var sum = orig.reduce(function(cum, val) {
    return cum + val;
}, 0);
console.log(sum);    // 15

These are specialized iterators. You can use them when this type of output is exactly what you want. They are less flexible than a for loop (for example, you can't stop the iteration in the middle like you can with a for loop), but they are less typing for specific types of operations and for people that know them, they are likely a little easier to see the code's intent.

I have not myself tested the performance of .map() and .reduce() versus a for loop, but have seen tests for .forEach() which showed that .forEach() was actually slower in some browsers. This is perhaps because each iteration of the loop with .forEach() has to call your callback function, whereas in a plain for loop, you do not have to make such a function call (the code can be directly embedded there). In any case, it is rare that this type of performance difference is actually meaningful and you should generally use whichever construct makes clearer, easier to maintain code.

If you really wanted to optimize performance, you would have to write your own test case in a tool like jsperf and then run it in multiple browsers to see which way of doing things was best for your particular situation.


Another advantage of a plain for loop is that it can be used with array-like objects that support indexing, but do not support .reduce() and .map().

And, a for/of loop can be used with any object that implements the iterator protocol such as HTMLCollection.

Solution 3:

This is like asking if I like basketball or football better. Both have their positives.

If you have 10 developers look at your for loop, 9 out of 10 will know what you are doing right away. Maybe half will have to look up what the map() method is, but then they'll also know what's going on. So in this respect, a for loop is easier for others to read.

On the flip side, map() will save you two or three lines of code.

As far as performance goes, you'll find map() is built internally with something akin to a for loop. You might see a few milliseconds of difference when it comes to performance speeds if you run them through large iterations; but they'll never be recognizable to an end user.

Solution 4:

forEach(): Executes a provided function(callback) once for each array element. Doesn’t return anything (undefined) but this callback is allowed to mutate the calling array.

map(): Executes a provided function(callback) once for each array element and creates a new array with the results of this executions. It cannot mutate the calling array content.

Conclution Use map() when you need to return a new array, use forEach() or for when you want to change the original array.

Solution 5:

Bumped into this while searching for something else. So trying to answer it even if it is a old thread as the concepts applies no matter what.

If you consider performance and flexibility, "for" loop always beats the others, just because it doesn't have the overhead of calling a function for each iteration and can be used for any purpose.

But, there are other gains with functions like forEach, map, reduce etc (let's call them functional methods). It is mainly the readability, maintainability.

Below are few drawbacks of for loop

  1. Introduces new variables to the scope, just for the counter/iteration
  2. Hard to debug errors, due to un-intentional changes to counter variables. This becomes more difficult and the chances to make a mistake increases more as the number of loops with in loops increase
  3. Developers have the habit of using loop variables as i, j, k. It is very easy to lose the track of which counter and which inner loop the code is executing once the loop increases certain lines of code
  4. With ES6, we have at least limited/local scope introduced by 'let'. But before, the variables introduced by for loop have a function scope causing even more accidental errors

To avoid all of these, it is suggested to use functions like forEach, map, reduce when you know what you have to do (Not to forget most of these functional methods offer immutability). A small sacrifice in terms of performance for the greater good and more succinct code.

With ES6, most of the functional methods are supported by the language itself. They are optimised and we don't have to rely on libraries like lodash (unless there is a severe performance gain).

Post a Comment for "When/why To Use Map/reduce Over For Loops"