The while Loop

Imagine you need to print the numbers from 1 to 100. You could write console.log() a hundred times, but it would take ages, and changing anything later would be even worse. Programs need to repeat work like this all the time: go through every student in a list, check every product in a shop, or redraw a game screen 60 times a second. That is what loops are for. A loop is a piece of code that runs again and again.

The simplest loop is while. It repeats a block of code while its condition is true:

let number = 1;
while (number <= 5) {
    console.log(number);
    number = number + 1;
}

This prints:

1
2
3
4
5

A while loop looks like an if: the keyword, a condition in parentheses and a block of code in curly braces. The difference is that if runs its block at most once, but while keeps coming back to the condition. Step by step:

  1. The program creates number with the value 1.
  2. It checks the condition number <= 5. It is true, so it runs the block: it prints 1 and increases number to 2.
  3. It goes back to the condition. 2 <= 5 is still true, so it prints 2 and increases number to 3.
  4. And so on, until number is 6. Then the condition is false, the loop ends and the program continues with the code after the loop.

Each run of the block is called an iteration. This loop has five iterations. To print the numbers up to 100, you would only change 5 to 100.

Watch out for loops that never end. If you forget the line number = number + 1;, number stays 1, the condition is always true and the loop prints 1 forever. This is called an endless loop (or an infinite loop). In these exercises, such a program is stopped after 5 seconds with the message The program ran too long and was stopped. Does it have a loop that never ends? When you see it, check that the loop changes the variable in its condition, so that the condition becomes false at some point.

Instructions

Create a variable number with the value 10. Use let, because the loop will change its value.

Below it, write a while loop that runs while number is less than or equal to 20. Inside the loop, print number and then increase it by 1. The program prints the numbers from 10 to 20, each on its own line.

Now change one number in your code so that the loop prints all the numbers from 10 to 100.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

1/12

Next