Difference between map, filter vs for and forEach and what would be the advantages of using map and filter over For and forEach loops?

Viewed 5565

I have gone through the map and filter functionalities and got to know that there is some kind of differences and advantages over for and foreach.

Advantages:

  1. No need to write too much of code and very clear understanding

  2. Better performance compare to iteration

how map and filter will be the better performance ?

appreciate any kind of suggestions.

4 Answers

Clear explanation about performance and differences of for, for each, map and filters freeCodeCamp

The performance of map and filter are not always better than for loops.
This article explains everything in great details map vs for loop

Read it from start to end and you get complete understanding of the difference, advantages and disadvantages of each.

Other answer's actually explains the reasons. Here is a simple bench marking example. Use the link to run the test.

http://jsben.ch/cz0Cg

Posting the results in case if link expires.

JS For Loop

var foo1 = ['spray', 'limit', 'elite', 'exuberant', 'destruction','present'];
for(var i=0;i<foo1.length;i++){
    console.log(foo1[i]);
}

Execution time : 677 ms

JS Map

var foo2 = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
foo2.map((v,i)=>console.log(v));

Execution time : 686 ms

JS Filter

var foo3 = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = foo3.filter(word => word.length > 6);

console.log(result);

Execution time : 259 ms

Execution Time given is when I tested, it is subject to change.

There is no pros and cons in using map or forEach. They have their own purposes.

The main difference between this two methods is that forEach allows you to change elements of original array and returns undefined and map does not allow you to change original array and intended for making new array based on original one.

For example if you need to get array of user ids from array of users you should use map and if you need console.log something from each item of array, you should better use forEach.

As javascript is more functional language it preferably to use non-mutating functions from Array.prototype such as filter, map, find ect. It allows me to make code more readable and maintainable. I can write construction like tat one

arr.map(num => num * 2).filter(num => num > 5);

You can learn more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

P.S. for each forEach in my project there are 20 or more usages of map I avoid using mutable methods.

Related