compuhelpindia.com

JavaScript For Loop

Compuhelpindia.com
« Previous                                                                                                                                       Next Chapter »

Loops can execute a block of code a number of times.
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:
Eaxmple:
<!DOCTYPE html>
<html>
<body>
<script>
function compu()
{
var i;
for(i=0;i<5;i++)
{
alert("Compuhelp");
}
}
</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 For Loop
The for loop is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
Example:
<!DOCTYPE html>
<html>
<body>
<script>
function loop()
{
var x="";
for (var i=0;i<5;i++)
{
x=x + "The Compuhelp is " + i + "<br>";
}
document.getElementById("demo").innerHTML=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.

The For/In Loop
The JavaScript for/in statement loops through the properties of an object:
Example:
<!DOCTYPE html>
<html>
<body>
<script>
function forloop()
{
var n,m;
for(n=0;n<3;n++)
{
for(m=0;m<3;m++)
{
alert("compuhelp");
}
}
}
</script>
<p>Click one of the buttons to call a function</p>
<button onclick="forloop()">Click for Compuhelp</button>
</body>
</html>  
 

Click one of the buttons to call a function