CodeRigor

LESSON

Repeat steps with for and while

Repeat a block a fixed number of times with for, repeat until a condition changes with while, keep counts and running totals, and avoid off-by-one mistakes.

Computers are good at doing the same thing many times without getting bored or making slips. A loop is a statement that runs a block of code repeatedly. This lesson covers the two loops you will use most.

for repeats a fixed number of times

This program prints the same line three times.

JavaScript
for (let i = 0; i < 3; i++) {
  console.log("Hello");
}
console.log("Done");

It prints Hello three times and then Done.

The first line of a loop, up to the opening {, is its heading. In the heading, the round brackets after for hold three parts, separated by semicolons:

  1. let i = 0 is the start. It runs once, before anything else, and creates a variable that counts the repetitions. This variable is called the loop variable.
  2. i < 3 is the condition. It is checked before every repetition. While it is true, the block runs. When it is false, the loop ends.
  3. i++ is the step. It runs after every repetition. i++ adds 1 to i; it is a short way to write i += 1.

Each run of the block is called an iteration.

The three parts of a for loop
start / 4
The start runs once. Then the loop goes round: check the condition, run the block, do the step, and check again. A false condition is the only way out.
The three parts of a for loop
The start runs once. Then the loop goes round: check the condition, run the block, do the step, and check again. A false condition is the only way out.

The loop variable counts

The block can use the loop variable. Its value is different on each iteration.

JavaScript
for (let i = 0; i < 3; i++) {
  console.log(i);
}

This prints 0, 1 and 2. The loop runs three times, and the count starts at zero, so it stops before 3.

To count from 1 to 3 for a person to read, start at 1 and use <= so that the last value is included:

JavaScript
for (let position = 1; position <= 3; position++) {
  console.log(`Seat ${position}`);
}

This prints Seat 1, Seat 2 and Seat 3. The loop variable can have any name. i is a common short name when the number is only a counter; a name such as position is better when the number means something.

A running total

A very common pattern: start a variable at zero before the loop, and add to it on every iteration. The variable is called a running total.

JavaScript
let total = 0;
for (let number = 1; number <= 3; number++) {
  total += number;
}
console.log(total);

This prints 6, which is 1 + 2 + 3. Step through the diagram to watch number and total change.

A loop variable and a running total
start / 9 ⇄ code
Line 3 runs three times. Each time, number has the next value and total grows by it. Line 5 runs once, after the loop.
A loop variable and a running total
Line 3 runs three times. Each time, number has the next value and total grows by it. Line 5 runs once, after the loop.

The line let total = 0; must be before the loop. The total has to keep its value from one iteration to the next, and it is used after the loop ends.

Looping over typed lines

The loop variable can be a position in the array of typed lines. This program adds up every number the user typed after a first line that says how many there are.

JavaScript
const typed = "3\n4\n10\n1";   // stands in for four typed lines
const lines = typed.split("\n");

const count = Number(lines[0]);
let total = 0;
for (let position = 1; position <= count; position++) {
  total += Number(lines[position]);
}
console.log(total);

This prints 15. The count is lines[0], so the numbers themselves are at positions 1, 2 and 3: exactly the values that position takes.

while repeats until a condition becomes false

A while loop has only a condition, like if. JavaScript checks the condition; if it is true, it runs the block, then goes back and checks again. The loop ends when the condition is false.

JavaScript
let countdown = 3;
while (countdown > 0) {
  console.log(countdown);
  countdown -= 1;
}
console.log("Lift off!");

This prints 3, 2, 1 and then Lift off!. countdown -= 1 subtracts 1, in the same way that += 1 adds 1.

Use for when you know the number of iterations before the loop starts. Use while when you cannot say in advance how many there will be. This program looks through the typed lines until it finds the right word:

JavaScript
const typed = "open\nplease\nsesame";   // stands in for three typed lines
const lines = typed.split("\n");

let wrong = 0;
while (lines[wrong] !== "sesame") {
  console.log(`${lines[wrong]} is not the word.`);
  wrong += 1;
}
console.log(`Welcome. Wrong tries: ${wrong}`);

This prints open is not the word., please is not the word. and Welcome. Wrong tries: 2.

Notice that the block changes wrong, so each check of the condition looks at the next line. If nothing in the block could change the condition, the loop would run for ever. That is called an infinite loop. This one never stops, because n stays at 1:

JavaScript
let n = 1;
while (n < 5) {
  console.log(n);
}

There is no error message for an infinite loop: the program keeps printing 1. On this site a program that runs too long is stopped for you. On your own computer, press Ctrl+C in the terminal to stop it. The repair is to change n inside the block, for example with n += 1;.

The word-finding program above has the same weakness: if the user never types sesame, the positions run past the end of the array, every further element is undefined, and the loop never ends. A loop that depends on input needs input that lets it finish.

Off-by-one mistakes

The most common loop mistake is to run one time too many or one time too few. It is called an off-by-one mistake. Compare these loop headings:

Heading Values of i Iterations
for (let i = 0; i < 3; i++) 0, 1, 2 3
for (let i = 1; i <= 3; i++) 1, 2, 3 3
for (let i = 1; i < 3; i++) 1, 2 2
for (let i = 0; i <= 3; i++) 0, 1, 2, 3 4

The first two are the usual ways to repeat three times. The last two each mix them up. When a loop gives a wrong count, write down the first value of the loop variable and the last value for which the condition is still true.

Two errors you will meet

Declaring the loop variable with const.

JavaScript
for (const i = 0; i < 3; i++) {
  console.log(i);
}
Text
0
/work/main.js:1
for (const i = 0; i < 3; i++) {
                          ^

TypeError: Assignment to constant variable.
    at Object.<anonymous> (/work/main.js:1:27)

The first iteration works and prints 0. Then the step i++ tries to change i, and the ^ points at it. A loop variable changes, so it must be declared with let.

Using the loop variable after the loop.

JavaScript
for (let i = 0; i < 3; i++) {
  console.log("Hello");
}
console.log(i);
Text
Hello
Hello
Hello
/work/main.js:4
console.log(i);
            ^

ReferenceError: i is not defined
    at Object.<anonymous> (/work/main.js:4:13)

A variable declared in the heading of a for loop, or with let or const inside a block, exists only inside that loop or block. Line 4 is outside, so the name is unknown there. A value that is needed after the loop, such as a total, must be declared before the loop.

What you can do now

You can repeat a block a fixed number of times with for, repeat until a condition changes with while, keep a running total, and check the first and last values of a loop variable. In the exercises you will trace loops by hand, then write a program that adds up the numbers its user types.

Next: write functions and finish a complete program, the last lesson of this unit.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Starts at chapter 19, 'While loops' (2:26:41), about eight minutes, and continues into chapter 20, 'For loops' (2:34:53), about six minutes. Where the video takes input from a web browser, read it as a typed line; the loops themselves are the same in Node.