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 Create an Array of Objects

I need clarification on the totalValue function.

From the workspace instructions and video, as I understood it, Dave wants us to get the total value of all products in the array. Doesn't the code in the solution only calculate the total price of inventory for that item, not for the full array?

Here is the code I have for calculating the totalValue of all items in the product array.

function totalValue(arr) {
  let totalPrice = 0;
  for (let i=0; i < arr.length; i++) {
    let inventoryPrice = arr[i].inventory * arr[i].unit_price
    totalPrice += inventoryPrice
  }
  return totalPrice.toFixed(2);
}

1 Answer

Steven Parker
Steven Parker
229,732 Points

Other than the creation of an intermediate variable, this is essentially the same as the solution shown in the "Teacher's Notes" section of the page below the video. But the addition of the ".toFixed(2)" is a nice touch. :+1:

Initially when reading the teachers solution, I was reading his code as only getting the price of the individual items. After looking again I realize that you are correct.