SQL PHP HTML ASP JavaScript articles and free scripts to download
JavaScript Tutorials
Popular Tutorials
Drop down list
Timer function
JavaScript Tutorials
String
Array
Date & Time
Form Validation
Event Handling
Math Functions
JavaScript Forum
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.

 
 

While loop and do loop

While loops are conditional loops where a condition is checked at the starting of the loop and if the condition is true then the statements inside the loop is executed. So the changes required in condition has to be inside the statement, otherwise the loop may go for infinite looping. For easy understanding we can say While True Loop. This means as long as the expression is turn go for the loop.

You can also see PHP while loop, ASP will loop which have more or less similar purpose and to some extent similar syntax.

Here is the basic syntax for while loop in JavaScript.

While ( expression )
{
statements;
}

Note that here the expression is checked or evaluated before starting of the loop so if the condition returned is FALSE then the loop will never be executed.

Let us try with this example which prints

var i=0;
while (i <= 5)
{
document.write(i+"<br>")
i++;
}

The above code will print 0 to 5 with a line break after each number.

We can use break statement inside a while loop to come out of the loop. Here it is

var i=0;
while (i <= 5)
{
document.write(i+"<br>")
if(i>2){break;}
i++;
}


Do While Loop
Do While loop is little different than while loop. Here the condition is checked at the end of the loop. So even if the expression is FALSE then also once the statements inside the loop will be executed. This is the basic difference between do while loop and while loop. Here is an example of Do While loop in JavaScript.

var i=0;
do
{
document.write(i+"<br>")
i++;
} while (i <= 5)


In the above code condition is checked at the end of the loop only. Here also we can use break statement to come out of the loop. Here is the example

var i=0;
do
{
document.write(i+"<br>")
if(i>2){break;}
i++;
} while (i <= 5)
Further readings
For Loop with break statement
Do While Loop with break statement in JavaScript
Switch statement
If Else
 
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.

Scripts
PHP
JavaScript