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()

Sergio Leon
Sergio Leon
12,594 Points

I don't understand how the sum of prices was done

const prices = [6.75, 3.10, 4.00, 8.12]; let total = 0;

prices.forEach(price => { total += price; });


Where does that ''price'' we are adding to the total let variable come from?

Thanks in advance

2 Answers

Dave StSomeWhere
Dave StSomeWhere
19,822 Points

It is being defined at it's first occurrence, as part of the Arrow Function

I think of it the same as when I define a variable name for function parameter. Then, that variable name is used within the function scope. It is just simplified with the arrow function syntax.


anonFunction = function(price) {
    // code goes here - and you can use price

Is that what you were questioning?

Daniel Boisselle
Daniel Boisselle
Front End Web Development Techdegree Student 17,438 Points
const prices = [6.75, 3.10, 4.00, 8.12]
let total = 0

// forEach is a method that takes an anonymous function
// and invokes it over each value in the array
// where currentPriceValue is just an arbitrary placeholder for the current value
// this function can take a second argument that will also represent the index
// It will start at 0 up until the last index which is 3

prices.forEach(function(currentPriceValue, index) {
  console.log(`Current total: ${ total} current price: ${currentPriceValue} at index ${index}`)
  total = total + currentPriceValue 
  // the line above we reassign the current value of total and add it to the current price
  console.log(`This is the new total ${total}`)

// fat arrow syntax

price.forEach(price => total += price)

// this is shorthand for the function above, without the index paramater
// try running this code for yourself in a treehouse workspace or repl.it