Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?

Forums JavaScriptCan you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?
Staff asked 2 years ago

Answers (1)

Add Answer
Krushit Sachapara Marked As Accepted
Staff answered 2 years ago

map():

The map() method receives a function as a parameter. Then it applies it to each element and returns an entirely new array. This means that it returns a new array that contains an image of each element of the array.

forEach():

The forEach() method receives a function as an argument and executes it once for each array element. However, instead of returning a new array like map(), it returns undefined.

 

Since the main difference between them is whether or not there is a return value, you would want to use map() to make a new array and use forEach() just to map over the array.

Subscribe

Select Categories