1. For Loop
The for loop is used when you know in advance how many times the script should run.Syntax
For (initialization, condition, increment){
Statements
}
Example
<script type="text/javascript">var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br >");
}
</script>
2.While Loop
The while loop loops through a block of code while a specified condition is true.Syntax:
while (Condition){
repetitive statements
}
Example:
<script type="text/javascript">var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br >");
i++;
}
</script>
3.Do...while Loop
This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.Syntax
do{
repetitive statements
}
while (condition)
Example
<script type="text/javascript">var i=0;
do
{
document.write("The number is " + i);
document.write("<br>");
i++;
}
while (i<=5);
</script>
The break Statement
The break statement will break the loop and continue executing the code that follows after the loop (if any).Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
The continue Statement
The continue statement will break the current loop and continue with the next value.Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br >");
}
</script>
</body>
</html>