while and do-while Loops

|

while and do-while Loops
Two additional repeat loops are available in JavaScript. The while loop tests the supplied condition and continues to execute until it is met. Here is the syntax for it.

Syntax:
while (condition){
statement(s)
}

Example:
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>

Result:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

Do-while loop:
The primary difference between these while and do-while loop is that the "do-while loop" will always execute one time whether the condition is true or not whereas the "while loop" will only execute if the condition is true.

Syntax:
do{
statements
} while (condition)

Example:
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>

Result:
The number is 0




 

©2009