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

Sum and Average

Now that you can go through an array, let's look at what loops are used for most often. The first pattern adds everything up. Say you have the prices of the things in your shopping cart and want the total:

const prices = [120, 45, 300, 85];
let total = 0;
for (const price of prices) {
    total += price;
}
console.log("Total:", total);
Total: 550

The variable total collects the sum. It starts at 0, because before you add anything, the sum is zero. In each iteration, total += price adds one price: after the first iteration, total is 120, then 165, 465 and finally 550.

Where each line goes matters:

  • let total = 0; goes before the loop, so that it is created only once. If you created it inside the loop, it would start from 0 again in every iteration, and after the loop it wouldn't exist at all: ReferenceError: total is not defined.
  • It must start at 0. With just let total;, it would start as undefined, and undefined plus a number gives NaN (“Not a Number”).
  • console.log() goes after the loop, when the sum is complete. Inside the loop, it would print every partial sum: 120, 165, 465, 550.

The average is the sum divided by the number of values, and the number of values is the length of the array:

const average = total / prices.length;
console.log("Average:", average);
Average: 137.5

Use prices.length rather than the number 4. When you add another price to the array, the average will still be right.

Instructions

  1. 1

    The array readingMinutes holds how many minutes you read on each day of one week. Create a variable total with the value 0. Then go through the array with a loop and add each value to total with +=.

  2. 2

    After the loop, print the sum with console.log("Total:", total);. The output is Total: 280.

  3. 3

    At the end of the program, create a variable average with the average: total divided by the length of the array. Print it as Average: 40.

Back

5/12

  1. 1. The while Loop
  2. 2. Shorter Notation
  3. 3. The for Loop
  4. 4. Looping Through Arrays
  5. 5. Sum and Average
  6. 6. Counting
  7. 7. The Largest Value
  8. 8. The break Statement
  9. 9. The continue Statement
  10. 10. Loops and Text
  11. 11. Nested Loops
  12. 12. Summary
Next

Try it yourself

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