Home > Article > Web Front-end > Detailed explanation of usage examples of JavaScript basics while loop and do while loop
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 }
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>
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 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);
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>
This will produce the following results:
Starting Loop Current Count : 0 Loop stopped!
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!