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 trialTommaso Poletti
5,205 PointsWhy use .map() instead of .forEach()
In this video @Jim Hoskins for iterate the array of object in React use .map().
I know the basic differences between the two methods (.map() || .forEach() || for()).
Is a simple preference or there are a deep meaning? :)
// array of object
var PLAYERS = [
{
name: "polettit",
score: 31,
},
{
name: "mantovanig",
score: 13,
},
{
name: "cantellid",
score: 33,
},
];
// where he use map()
props.players.map(function(player) {
return <Player name={player.name} score={player.score} />
})
Thanks in advance ;)
Tommy
1 Answer
Steven Parker
231,271 PointsUse map when you need the return values of the function.
Both map and forEach call a function for every element of the array, but only map builds a new array using the function return values.
So if you need the return values, use map; and if you don't, use forEach.