Interactive online courses HTML Academy
2026-03-09 14:07 Diff

Before that, we wrote loops inside the conditions, but you can also do it vice versa! If you add a condition inside the loop, it will be checked at each iteration.

For example, you can check the value of the counter, and if it is greater than two, add 3, and not 2 to the sum.

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

Program result:

LOG: 2 (number) LOG: 4 (number) LOG: 7 (number) LOG: 10 (number) LOG: 13 (number)

We will practice adding conditions to loops. Add a check to our loop from the previous task. If the value of the counter is greater than 5, add number 2 to sum.