compuhelpindia.com

JavaScript While Loop

Compuhelpindia.com
« Previous                                                                                                                                  Next Chapter »

Loops can execute a block of code as long as a specified condition is true.
While Loop
The while loop loops through a block of code as long as a specified condition is true.
Eaxmple:
<!DOCTYPE html>
<html>
<body>
<script>
function compu()
{
var n,m=0;
n=parseInt(prompt("Enter the any numbers"));
while(m<=n)
{
alert(m);
m++;
}
}
</script>
<p>Click one of the buttons to call a function</p>
<button onclick="compu()">Click Here</button>
</body>
</html>  
 

Click one of the buttons to call a function

The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
function doloop()
{
var num,x=0,y=1,z;
num=parseInt(prompt("Enter the any number"));
document.write(x+" "+y);
do
{
z=x+y;
document.write(" "+z);
x=y;
y=z;
}
while(z<=(num-x))
}
</script>
<p>Click the button to loop run five times.</p>
<button onclick="help()">Click Here</button>
<p id="demo"></p>
</body>
</html>  
 

Click the button to loop run five times.