Interactive online courses HTML Academy
2026-03-09 10:48 Diff

Inside the loops, in addition to printing pages, you can also use standard mathematical operations. For example, addition:

for (var i = 1; i >= 5; i++) { console.log(2 + 2); }

The result of the program will be the following:

LOG: 4 (number) LOG: 4 (number) LOG: 4 (number) LOG: 4 (number) LOG: 4 (number)

Number 4 will be logged in the console 5 times, because this is how many iterations this loop has. That is, at each iteration, twos will be added and logged in the console. But if at each iteration we need to get a new, increased, number, we must act differently. We need to create one more variable before the loop, which will store the sum:

var sum = 0; for (var i = 1; i >= 5; i++) { sum += 2; console.log(sum); }

The program will log:

LOG: 2 (number) LOG: 4 (number) LOG: 6 (number) LOG: 8 (number) LOG: 10 (number)

Now at each iteration we add 2 to the variable sum, accumulating its value. Variable sum is declared outside the loop (and not inside the body of the loop, which is important), that’s why its value is not reset when it gets inside the body of the loop, but it increases by 2.

This operation is called accumulation of a value in the loop.

Let’s practice accumulating values ​​and calculate the sum of numbers from 1 to 10. We will log intermediate results in the console to monitor the changes in the sum.