Rajan Kumar

rajan

Founder & Programmer at HackersFriend Updated March 9, 2020, 12:28 a.m. ⋅ 103 views

forEach() Vs map() in JavaScript - Things every developer should know


Javascript offers two methods to iterate over an array forEach()  and map().

They are both used for the same purpose - iterate over an array but they are very different. But it becomes confusing to developers, specially beginners.

Javascript has a high reputation of surprising developers. 

 

In this article, I am going to clearify the differences of both of the methods and places where they should be used.

  • map()

map() method takes an function as input argument and applies this function to every element of the array and returns a new array, which is of the elements which it got after applying function to it. So, if you give the function that doubles the element, then new array would be of elements having double of everyone of it.

Have a look at this example:

const myArray = [5, 4, 3, 2, 1]

myArray.map(x => x * 2)

// >>>>>>>>>>>>>>>>> Output: [10, 8, 6, 4, 2]

 

  • forEach()

forEach() also, takes a function as an argument and applies it and just gives the output or whatever you want, but it doesn't returns anything neither does it modifies the value of existing array.

Have a look at this example:

const myArray = [1, 2, 3, 4, 5]
myArray.forEach(element => console.log(element * 2))

// >>>>>>>>> Output : 2
//                    4
//                    6
//                    8
//                    10

 

If you try to access the value returned for forEach() , it will throw undefined error.

const myArray = [1, 2, 3, 4, 5]
myArray.forEach(x => x * 2)
//>>>>>>>>>>>>>return value: undefined

myArray.map(x => x * 2)
//>>>>>>>>>>>>>return value: [2, 4, 6, 8, 10]

 

Since, forEach() doesn't returns anything you cannot chain it with any other function like reduce(), sort(), filter() While you can do it with map().

const myArray = [1, 2, 3, 4, 5]
myArray.forEach(x => x * 2).reduce((total, value) => total + value)

//>>>>>>>>>>>>> Uncaught TypeError: Cannot read property 'reduce' of undefined


myArray.map(x => x * 2).reduce((total, value) => total + value)

//>>>>>>>>>>>>>return value: 30

 



arrow_upward Upvote

comment Comment

arrow_downward downvote



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details