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

JavaScript

Why 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.

The '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

1 Answer

Each 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