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
5A 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:
- The program creates
numberwith the value1. - It checks the condition
number <= 5. It istrue, so it runs the block: it prints1and increasesnumberto2. - It goes back to the condition.
2 <= 5is stilltrue, so it prints2and increasesnumberto3. - And so on, until
numberis6. Then the condition isfalse, 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.