While Loop
The first type of loop we will look at is the while
loop. Imagine you want to print the numbers 1-100. Doing this manually would take a long time. We can simplify this using a while
loop:
let number = 1;
while (number <= 100) { // While number is less than or equal to 100
console.log(number); // Print number
number = number + 1; // Increase number by 1
}
You can see that the while
loop has a similar structure to the if
statement.
It works as follows: after the word while
comes a condition which, as long as it is true, the block of code inside the while
loop will repeat. To remind you, a block of code is the code inside curly braces {}
following statements like if
, else
, or while
.
Our code will perform the following steps:
- Set the value of the variable
number
to 1. - Check if
number
is less than or equal to 100. - If yes, print the value of the variable
number
, increase its value by 1, and return to step 2. - If not, the program will end.
Notice that if we forgot to increase number
by 1 in our loop, number
would always be 1, and our loop would repeat indefinitely. This would cause a program that does not respond and would probably terminate itself after a while. This is always undesirable, and as programmers, we must be careful to avoid this error.
Instructions
Create a variable number
with a value of 10.
Create a while loop that prints the numbers from 10 to 20 using the number
variable.
Don't forget to increase the number
variable by 1.
Start programming for free
2/9