The while statement is a loop executing kind of a statement used to pre-test flow conditions.

The while loop statement is called a pretesting because the expression is tested before the loop starts and if it fails, the loop will never initiate, as shown in the example:

while (expression) {

   statement;

}

Or in the real numbers example:

var counter = 50;

var i =4;

for (i<counter) {

   alert(i);

   i += 7;

}

In the example above, the variables (counter, limit) must be initialized before the loop starts testing for the expression. If the expression evaluates to true (above: i < counter), the loop starts by showing the current value, and increasing it for "7", after which the next loop starts. The iteration will last till the counted number (i) reaches the limit (counter).

Example

The example with while statement in JavaScript:

x
 
<!DOCTYPE html>
<html>
<head>
<title>JS tutorial</title>
<style type="text/css">
body {
    margin-top:10px; padding:0px;
    background-color:#222; color:#bbb;
}
input {
    padding:4px;
    font-family:"Arial", sans-serif; font-size:1.0em; color:#223;
    cursor:pointer;
}
</style>
<script type="text/javascript">
    function whileLoop() {
        var i = 4;
        var counter = 50;
        var note = document.getElementById("note"); 
        var result = document.getElementById("result");
        result.textContent = ""; 
        note.textContent = "step=7, counter=50";
        while (i < counter) { 
            result.textContent += i + ",\n";    
            i += 7;
        }
    }
</script>   
</head>
<body>
    <h5>Start the counter and see the <i>while</i> statement in action:</h5>
    <form action="" method="post">
    <input type="button" onclick="whileLoop()" value="START" />
    </form>
    <pre id="note"> </pre>
    <pre id="result"> </pre>
</body>
</html>

 

›› go to examples ››