Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,777 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.