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: 550The 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 justlet total;, it would start asundefined, andundefinedplus a number givesNaN(“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.5Use prices.length rather than the number 4. When you add another price to the array, the average will still be right.
Instructions
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 +=.
After the loop, print the sum with console.log("Total:", total);. The output is Total: 280.
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.
Start programming for free
5/12