Tutorials  Articles  Notifications  Login  Signup


RK

Rajan Kumar

Founder at HackersFriend Updated March 9, 2020, 12:28 a.m. ⋅ 1123 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

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account