Explain the use of JavaScript while loop _ basics

Source: Internet
Author: User

When writing a program, there may be a situation when you need to perform some actions over and over again. In such cases, you need to write a looping statement to reduce the number of code.

JavaScript supports all the necessary loops to help you in all programming steps.
While Loop

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

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

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

The following example illustrates a basic while loop:

<script type= "Text/javascript" >
<!--
var count = 0;
document.write ("Starting Loop" + "<br/>");
while (Count < ten) {
 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 Cycle:

The Do...while loop is similar to a while loop, except that the conditional 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 is executed while
(expression);

Notice that a semicolon is used at the end of the do ... while loop.
Example:

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

<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! 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.