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.
PartWhen it runsIn the loop above
InitialiserOnce, before the first testlet i = 0
ConditionBefore every pass, the first one includedi < 4
UpdateAfter each pass, just before the next testi++

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.

Definite iteration

A for loop is the standard example of definite iteration. Its header names a starting value, a stopping test and a step, and those three settle how many passes there will be on their own. A loop whose repeat count depends on what happens while it is going, such as one that keeps reading input until the user types a particular word, is indefinite iteration, and that comes later.