Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,738 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,778 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.