The while loop is different from a for loop in the respect that it is known ahead of time how many times a while loop will execute. Suppose you ask the user for some input, the user may not enter the value you seek in the first try. So using a while loop, we would keep requesting for the right input. But if you use a for loop, you would be limited to asking only once, twice, or however many times you use. The point is with a for loop, you initially specify how many times the for loop is to be executed, but with a while loop that is not necessarily true.
The general syntax for creating a while loop is:
while (condition) {JavaScript statements that you want to execute repeatedly}wherecondition = a Boolean expression that can be true or false. While the Boolean expression is true, the JavaScript code inside the while loop is executed.
The following shows an example of a while loop:
<script language="javascript">var i = 1;while (i <= 5) {document.write (i + " ");i++;}</script>
Note that for a while loop we initialize our counter variable, i, before the loop starts. Note also the counter variable is updated inside the while loop. This while loop prints:
Table 2 shows more examples of while loops and their corresponding output.
| Table 2 more examples of while loop in use | |
|---|---|
| JavaScript while loop code | Output |
<script language="javascript">var i = 1;
// this while loop prints odd numbers between 1 and 10.while (i <= 10) {document.write (i + "<br>");i += 2;}</script>
|
|
<script language="javascript">var i = 2;
// this while loop squares i as long as i is less than or equal to 1024.while (i <= 1024) {document.write (i + "<br>");i *= 2;}</script>
|