The Counting for Loop
Three parts in one header
To repeat something a set number of times, you put three things in the loop header, separated by two semicolons:• an initialiser, which runs once, before anything else
• a condition, which is tested before every pass
• an update, which runs after each pass finishes
Read that as a sequence of small steps. Set i to 0. Test i < 4, which is true, so run the body. Run i++, making i equal to 1. Test again. The loop ends the first time the test fails, which happens when i reaches 4, so the body never runs with i equal to 4.
| Part | When it runs | In the loop above |
|---|---|---|
| Initialiser | Once, before the first test | let i = 0 |
| Condition | Before every pass, the first one included | i < 4 |
| Update | After each pass, just before the next test | i++ |
The condition comes first
Because the test happens before the body, a for loop is allowed to run zero times. If the condition is already false when the loop is reached, nothing in the body ever happens.Counting down, and counting in steps
The update does not have to add one, and the loop does not have to count upwards. It only has to move the loop variable toward failing the condition. When the loop runs backwards, the start value, the comparison and the update all flip together.The loop variable is gone afterwards
A variable declared with let in the header belongs to the loop and to nothing else. Once the closing brace is passed, the name no longer exists, and reading it throws a ReferenceError. It does not hold its final value and it is not undefined. If you need a number after the loop, declare that number outside the loop and change it inside.The program below prints each value
i takes and counts the passes. Run it, then make each change below and run it again. Press Reset before each change, so that each one starts from the original program.• Change
< to <=.• Set
end to 4, the same number as start.• Change
i++ to i += 2.const start = 4;
const end = 11;
let passes = 0;
for (let i = start; i < end; i++) {
console.log("i is " + i);
passes = passes + 1;
}
console.log("Passes: " + passes);
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.