Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Array Iteration Methods Array Iteration Examples Using forEach()

Frank keane
seal-mask
.a{fill-rule:evenodd;}techdegree
Frank keane
Full Stack JavaScript Techdegree Student 7,990 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?

thanks!

1 Answer

Sascha Bratton
Sascha Bratton
3,668 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.
});