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! While you're at it, check out some resources Treehouse students have shared here.
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 trialRemi Vledder
14,144 PointsIncorrect 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?
2 Answers
Bader Alsabah
4,738 PointsThe 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
33,778 PointsIn 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
.
brandon may
7,904 Pointsbrandon may
7,904 PointsFrom 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.