JavaScript AcademyProfessional Engineering

Learning object 11 of 100

For-loop execution explorer

Set a for loop's start, comparison, limit and update, and see every check of the condition, how many times the body runs, and when the loop ends.

Loading…

What it shows

A for loop checks its condition before every pass, so the condition is always checked once more than the body runs: the last check is the one that is false. If the update never moves the counter towards making the condition false, the loop never ends; the explorer stops after 200 passes and tells you.

Guided experiment

  1. Change <= to <. How many times does the body run now?
  2. Start at 10, compare with >=, limit 0 and update i -= 2.
  3. Set the update to i-- while counting up. What does the explorer report?

Predict

How many times does for (let i = 0; i < 4; i++) run its body?

Related

Lessons: Lesson 16: For loops, Lesson 18: Break and continue

Projects: Project 9: Shopping Cart Price Calculator

Source: web/assets/js/objects/object-011.js in the companion repository.