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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 15:56:47
Original
1529 people have browsed it

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
}

Copy after login

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>

Copy after login

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! 

Copy after login


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);

Copy after login

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>

Copy after login

This will produce the following results:

Starting Loop
Current Count : 0
Loop stopped! 

Copy after login

Related labels:
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template