Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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: 27

In 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. 1

    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.

  2. 2

    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.

Back

2/9

  1. 1. Shopping List
  2. 2. The Total
  3. 3. Adding Items
  4. 4. Checking the Input
  5. 5. Crossing Off Items
  6. 6. Items from a File
  7. 7. Saving the List
  8. 8. Removing Bought Items
  9. 9. Congratulations!
Next

Try it yourself

Do this exercise right here in your browser. No account needed.