Home >Web Front-end >JS Tutorial >Detailed explanation of the use of while loop in JavaScript_Basic knowledge

Detailed explanation of the use of while loop in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:56:471471browse

When writing a program, there may be a situation when you need to perform some operations over and over again. In this case, you need to write loop statements to reduce the amount of code.

JavaScript supports all necessary loops to help you in all programming steps.
while loop

The most basic loop in JavaScript is the while loop, which will be discussed in this tutorial.
Grammar

while (expression){
  Statement(s) to be executed if expression is true
}

The purpose of the while loop is to repeatedly execute a statement or block of code (as long as the expression is true). Once the expression is false, the loop will be exited.
Example:

The following example illustrates a basic while loop:

<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
while (count < 10){
 document.write("Current Count : " + count + "<br />");
 count++;
}
document.write("Loop stopped!");
//-->
</script>

This will produce the following results:

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 


do...while loop:

do...while loop is similar to a while loop, except that the condition check occurs at the end of the loop. This means that the loop will always execute at least once, even if the condition is false.
Grammar

do{
  Statement(s) to be executed;
} while (expression);

Note the use of semicolon at the end of the do...while loop.
Example:

For example, write a do... while loop program in the above example.

<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
 document.write("Current Count : " + count + "<br />");
 count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>

This will produce the following results:

Starting Loop
Current Count : 0
Loop stopped! 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn