While loops
Coding with JavaScript
🕑 This lesson will take about 15 minutes
A while loop repeats a block of instructions while a test condition evaluates to true. A while loop can repeat a set of instructions over and over again until the test condition evaluates to false and the loop exits. The rest of the program will then continue running. For example, we make a program that will ask a user to enter a password, and if they enter the wrong password, the program would keep asking until they enter the correct password.
Watch the video below and then scroll down for the sample code.
Example 1
In this example code, a variable is used as a counter and given an initial value of 1. While the counter variable is less than or equal to 10, a new paragraph of text will display on the screen. The counter will increase by 1 for every iteration of the loop. The web page will display ten paragraphs before the loop ends (once the counter reaches the value of 11), and each paragraph will have the counter number value appended to the end of it.
Here is the sample HTML and JavaScript code:
Example 2
In this example, the program asks the user to guess a secret number (a random number between 1 and 10). The while loop will keep asking the user to guess the correct number while they are getting it wrong.
It is important to provide an opportunity in the while loop for the test condition to eventually evaluate to false, otherwise, the loop will never stop running! This is called an infinite loop. An infinite loop occurs when the test condition always evaluates to true and nothing ever makes it evaluate to false such as a change in a variable’s value. Infinite loops will cause your program to crash and prevent the rest of the code from running.
Tip: You can also use the break; command to end a loop if a condition has been evaluated to true. You could use an if statement inside a while loop and then use the break; command to break the loop.
Next tutorial: Do…While loops