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
Write a function getTotal() that adds up the prices of all the items in items with a loop and returns the sum with return. With our three items, getTotal() returns 10.
At the end of showItems() (after the loop), show the total in the total element: total.textContent = getTotal();. The page then shows To pay: €10.
Start programming for free
2/6