Building Up a Total While Repeating
Introduction
Our loops can repeat a message or use the counter in a calculation. Another common job is to keep a running total: start with zero, add an amount during each pass, and report the final value after the loop.
The variable that remembers the total must be allowed to change, so we will declare it with let before the loop. Inside the loop, we will reassign it using its current value plus the new amount. We will finish the path with a small sales report that chooses a rate, repeats a sale, and checks whether the day was great or quiet.
Start a Total Before the Loop
Suppose the cafe sells five cups at four dollars and fifty cents each. We begin with a total of zero, then add the price once for every cup:
The loop runs five times. Each time, JavaScript works out the right side, then stores that value back into total. After the loop ends, the final print shows the amount from all five cups:
We declare total before the loop because the loop needs the same variable on every pass, and we print it after the loop because that is when all five additions are complete. If we declared total inside the block, each pass would start a fresh variable and the earlier amount would not carry over.
This pattern is called accumulation: each pass contributes a new amount to a value that already contains everything from earlier passes. We can read total = total + pricePerCup in two steps. First JavaScript looks up the current total and adds the price; then it stores the result back under total. After the first pass it is 4.5, after the second it is 9, and after the fifth it is 22.5. The let declaration is necessary because the value changes as the program runs.
See the Running Total
We can also print the amount inside the loop to watch it grow. The final print after the loop is still useful because it gives us one clear summary:
Each pass updates total first, then prints the updated value. After all three passes, the program prints the final total once more:
If the print came before the reassignment inside the loop, it would show the old amount on each pass. The order of those two lines matters: add first, then report the running value.
The print inside the loop is optional; it helps us see the steps but is not needed to calculate the final amount. The final print is outside the loop, so it runs once. We can compare the last running line with the final line and expect the amounts to match. If they do not, we can check whether the total was updated before it was printed and whether the loop ran the expected number of times.
