JavaScript while loop

The while loop loops through a block of code as long as a specified condition is true. The condition is evaluated before executing the statement.

In this tutorial, you will learn how to use the JavaScript while statement to create a loop that executes a block as long as a condition is true .

When the condition evaluates to false, the loop stops.

Syntax

while (condition/expression) {
  // code block to be executed
}

while loop evaluates the condition inside the parenthesis ().

The purpose of a while loop is to execute a statement or code block repeatedly as long as an  condition is true. Once the condition becomes false, the loop terminates.

The while statement evaluates the expression before each iteration of the loop.

Because the while loop evaluates the expression before each iteration, it is also known as a pretest loop.

When the condition evaluates to false, the loop stops.

Flowchart

JavaScript while loop flowchart

Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript while loop example</title>
</head>

<body>
    <h2>JavaScript While Loop</h2>

    <p id="demo"></p>

    <script>
        let text = "";
        let i = 0;
        while (i < 10) {
            text += "<br>The number is " + i;
            i++;
        }
        document.getElementById("demo").innerHTML = text;
    </script>
</body>

</html>
JavaScript while loop example

If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.