HTML Academy
Accumulation in the loop
Loops14/28
Back to the list of tasks
  • 1. New project: driver development
  • 2. Managing the number of copies
  • 3. Learning the for loop
  • 4. Correcting the loop
  • 5. Printing the pages in reverse order
  • 6. Printing only odd pages
  • 7. Printing only even pages
  • 8. Printing driver: copy mode
  • 9. Printing driver: all pages
  • 10. Printing driver: pages in reverse order
  • 11. Print driver: even and odd pages
  • 12. Print driver: switching evens and odds
  • 13. Accumulation in the loop
  • 14. Checks in loops
  • 15. Searching for an even number
  • 16. How much does printing cost?
  • 17. Economy printing
  • 18. Saving ink
  • 19. Summary of “Loops”. Part 1
  • 20. Third program: “Protein shake!”
  • 21. It’s been a “while”
  • 22. The while loop, summation
  • 23. Another project: a dart machine
  • 24. Dart machine: accumulating misses
  • 25. Dart machine: defeat
  • 26. Dart machine: final scoreboard
  • 27. Summary of “Loops”. Part 2
  • 28. Fourth program: “Mad Dryer”
Searching for an even number
  • Sign up
  • Log in

Loading…
Everything will be ready in few seconds

  • Theory
  • Theory
  • Comments

Checks in loops

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.

Comments

  • script.js
JavaScript
var sum = 0; for (var i = 1; i <= 10; i++) { // Add a condition here sum += i; console.log('i: ' + i); console.log('sum: ' + sum); }

What didn’t you like in this task?

Thanks! We’ll fix everything at once!

Console

The code has changed, click “Run” or turn autorun on.

Result

Goalscompleted
  1. Inside the loop, before increasing sum, add a check to make sure that i is greater than 5.
  2. If the condition is triggered, increase sum by 2.
  3. Add the else branch and transfer into it the string sum += i;.

Cookies ∙ Privacy ∙ License Agreement ∙ About ∙ Contacts ∙ © HTML Academy OÜ, 2019−2025

VISAMastercard

Log in

or

Forgot your password?

Sign up

Sign up

or
Log in

Restore access

Have you forgotten your password or lost access to your profile? Enter your email connected to your profile and we will send you a link to restore access.

Forgot to connect your email to the profile? Email us and we’ll help.