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!

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 JavaScript Array Iteration Methods Array Iteration Examples Using forEach()

Frank keane
Frank keane
8,074 Points

How does the price variable automatically get assigned to the current array item?

So, once inside the forEach, if you name a function it refers to the array item being dealt with for each iteration?

so price=6.75 then price = 3.10 etc?

it's just a convention, an automation?


1 Answer

Sascha Bratton
Sascha Bratton
3,671 Points

The function you pass to forEach creates a scope. The parameter to this function is the value of each item in the array. You may give this parameter a variable name and on each iteration of the loop, this variable will contain the value of the item for the current iteration.

So for, this array:

const prices = [6.75, 3.10];

If you give your function parameter the name price then it will have those values on the iterations:

prices.forEach((price) => {
  console.log(price); // 6.75, 3.10, etc.
Frank keane
Frank keane
8,074 Points

ah right so in forEach((price) => price is the parameter, not the name of the arrow function, gotcha. many thanks!