The while loop is an advanced programming mechenism that allows you to do something over and over while a conditional statement is true. Although the general uses of the while loop are usually a bit complex, this Java Script Academic Tutorial lesson will teach you the basics of how to create a while loop in Java Script.
while Statement
Any while statement executes its statements as long as a specified condition evaluates to true. A while statement looks like as follows:
while (condition)
statement
If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop.
The condition test occurs before statement in the loop are executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution stops and control is passed to the statement following while.
To execute multiple statements, use a block statement ({ ... }) to group those statements.
Example:1
The following while loop iterates as long as n is less than three:
n = 0;
x = 0;
while (n < 3)
{
n++;
x += n;
}
With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:
After the first pass: n = 1 and x = 1
After the second pass: n = 2 and x = 3
After the third pass: n = 3 and x = 6
After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.
Example:2
Avoid infinite loops. Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate. The statements in the following while loop execute forever because the condition never becomes false:
while (true)
{
alert("Hello, world");
}
The do...while Loop
The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested.
do
{
code to be executed
}
while (var<=endvalue)
Example:3
<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
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.