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 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; });

console.log(total);

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

Thanks in advance

2 Answers

Dave StSomeWhere
Dave StSomeWhere
19,870 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.

Like:

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

Is that what you were questioning?

Daniel Boisselle
seal-mask
.a{fill-rule:evenodd;}techdegree
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