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 trial
Thomas Dugan
8,021 PointsWhy does ```prices.forEach(price => { total += price; });``` work? We haven't defined 'price'
We have defined 'prices' but not 'price'. I want to understand why this solution works.
1 Answer
Henrik Christensen
Python Web Development Techdegree Student 38,322 PointsEach item in prices will be named price when it goes through the forEach
const prices = [5, 12, 42];
prices.forEach(price => { total += price; });
// round 1:
// prices[0] is now called 'price' and added to total
// round 2:
// prices[1] is now called 'price' and added to total
// round 3:
// prices[2] is now called 'price' and added to total
I hope this makes some kinda sense :-P
Trent Stenoien
Full Stack JavaScript Techdegree Graduate 21,632 PointsTrent Stenoien
Full Stack JavaScript Techdegree Graduate 21,632 PointsThe 'forEach' method of arrays takes a function with up to 3 parameters: current value ('price' here), index, and the array itself. So price is simply a given value within the array. Another way to write that function is as follows:
prices.forEach( function(price) {total += price;} );This article explains forEach() in more detail and might be helpful. https://www.w3schools.com/jsref/jsref_forEach.asp