Home > Web Front-end > JS Tutorial > Detailed explanation of usage examples of JavaScript basics while loop and do while loop

Detailed explanation of usage examples of JavaScript basics while loop and do while loop

伊谢尔伦
Release: 2017-07-21 14:01:54
Original
3531 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


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

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

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 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.
Syntax


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

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

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


<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

The above is the detailed content of Detailed explanation of usage examples of JavaScript basics while loop and do while loop. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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