While loops in JavaScript

A while loop runs a set of instructions (block of code) 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.

Take a look at the code below. A counter variable is 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 HTML code used for the two example JavaScript programs below:

<html>
    <head>
        <title>While loops</title>
        <script src="script.js"></script>
    </head>
        
    <body>

    </body>
</html>

In this first example, we have a program with a while loop that counts from 1 to 10 and displays these numbers. It starts at 1, and while the number is less than or equal to 10, it keeps increasing the counter by 1.

// Set the counter to 1
var counter = 1;

// Keep counting up by 1 until the counter reaches 10
while(counter <= 10){
    console.log(counter);
    counter++;
}

console.log("Goodbye!");

Here is the sample code for the second example program that 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.

// Let's generate a random number between 1 and 10
var secretnumber = Math.floor(Math.random() * 10) + 1;

// Let's ask the user to guess the secret number
var attempt = prompt("Enter a number between 1 and 10: ");

// Keep asking the user to guess the number while they get it wrong
while(attempt != secretnumber){
    attempt = prompt("Incorrect! Try again. ");
}

console.log("You got it!");

 

It is important to allow 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 evaluated to true. You could use an if statement inside a while a loop and then use the break; command to break the loop.

Next tutorial: Do..While loops