JavaScript Asynchronous Programming with JavaScript Understanding Promises Handle Multiple Promises with Promise.all

Remi Vledder
Remi Vledder
14,144 Points

Incorrect use of Array.prototype.map() in a few of Treehouse Javascript video's?

In a few video's I saw the teacher use the Array.prototype.map method for arrays which needed to be iterated.

However, as in the documentation, the map function returns an Array.

Does someone know the reasoning behind using .map() as for example the .forEach() (source) method?

From what i can tell, the map() method is used to select certain bits out of an array and store them in a new array. From there u can do whatever u want with the new array.

2 Answers

Bader Alsabah
Bader Alsabah
4,736 Points

The main motivation of using map() method is to not alter the original array. In a lot of applications you want to preserve the original array and create a new one with the modifications that you need. Therefore, map() will iterate through the specified array taking a callback function that will perform the modifications you need and return a new array without altering the original.

Gabbie Metheny
Gabbie Metheny
33,699 Points

In the case of generateHTML, I believe you could use forEach just fine, but in getProfiles you need to use map because you want a return value and forEach does not return anything. In general, I find map to be more flexible, and it chains nicely with itself and other array methods like filter and reduce, so that's probably at least part of why you see Treehouse using it more often than forEach.