The Total
A shopping list should also tell you how much the shopping will cost. You'll compute it with a function that goes through all the items and adds up their prices. It's the sum from the lesson on loops: a variable that starts at 0, and a loop that adds each value to it.
const numbers = [4, 8, 15];
let sum = 0;
for (const number of numbers) {
sum += number;
}
console.log(sum); // Prints: 27In the shopping list, the array holds objects, so you'll add up their price properties. And instead of printing the sum, the function gives it back with return, so that the code that calls it can use it, for example to show it on the page.
Where should the total be shown? At the end of showItems(). That function runs every time the list changes, so the total will always match the list.
Instructions
- 1
Write a function
getTotal()that adds up the prices of all the items initemswith a loop and returns the sum withreturn. With our three items,getTotal()returns10. - 2
At the end of
showItems()(after the loop), show the total in thetotalelement:total.textContent = getTotal();. The page then showsTo pay: €10.