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 trialPiotr Manczak
Front End Web Development Techdegree Graduate 29,363 PointsWhy did you use map() instead of let's say forEach() or for loop?
Why did you use map()
instead of let's say forEach()
or for loop? Is there any benefit of doing so?
3 Answers
Karolin Rafalski
11,368 PointsBoth .map()
and .forEach()
iterate over each item in an array.
.map()
returns a new array that you can save into a new variable.
.forEach()
goes over the array but doesn't save the changed values into a new array.
A for loop
is a great choice and can accomplish both things that .map()
and .forEach()
can accomplish (most of the time - an exception would be if you were using the React library where you have to use .map()
to accomplish certain things but that's a more advanced use-case).
Over time, as people get more comfortable with JavaScript/writing code, many people find .map()
and .forEach()
easier to read/understand what the code is trying to do and it's less likely you'll mistype: ie forgetting to put .length
as part of the control panel of your for loop
. There is also a for of
loop, which also has a nice and easy to read syntax as well. But in most cases, it is a coding-style preference.
A for loop can be a better choice if you don't need to iterate over every item (ie just the odd items, or every third, the first half...)
Piotr Manczak
Front End Web Development Techdegree Graduate 29,363 PointsThanks for taking your time to explain this to me. You are my hero.
RODRIGO MARTINEZ
5,912 Pointsclear answer. thanks