Home Basics Javascript while loop

Javascript while loop

a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

The while construct consists of a block of code and a condition/expression. The condition/expression is evaluated, and if the condition/expression is true,the code within all of their following in the block is executed. This repeats until the condition/expression becomes false.

Because the while loop checks the condition/expression before the block is executed, the control structure is often also known as a pre-test loop.

Compare this with the do while loop, which tests the condition/expression after the loop has executed.

Table of Contents

Syntax

while (expression) 
{
    // statement to be executed
}

 

Example

The example below first checks whether counter is less than or equal to 5, which it is, so then the {loop body} is entered, where the console.log is run and counter is incremented by 1.

After completing all the statements in the loop body, the condition, (counter <- 5), is checked again, and the loop is executed again, this process repeating until the variable counter has the value 5.

Note that it is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (such as a break statement) that controls termination of the loop. For example:

var counter = 1;

while (counter <= 5) 
{
    console.log('counter = ' + counter);
    counter++;
}

You should see something like this in the console

counter = 1
counter = 2
counter = 3
counter = 4
counter = 5

You can also loop through an array like this

var countries = ["France","Germany","Spain","Italy"];
total = 0;

while (total < countries.length) 
{
console.log("The country called " + countries[total]+ " exists");
total++;
}

You should see something like  this in the console

The country called France exists
The country called Germany exists
The country called Spain exists
The country called Italy exists

You may also like