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
- Change
<=to<. How many times does the body run now? - Start at 10, compare with
>=, limit 0 and updatei -= 2. - 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.