The for loop is used when you know in advance how many times the script should run.
for (variable=startvalue;variable<=endvalue;variable=variable+increment)
code to be executed
}Ex1:
<html>
var i=0;
for (i=0;i<=5;i++){
document.write("The number is " + i);document.write("<br />");
}</script>
</body></html>
Ex2:<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
For example, continue can be employed to display only the even numbers
between 1 to 20, skipping the odd numbers.
<script>
var msg = "";
for (var x = 0; x <=20; x++)
{
if (x%2)
{
continue;
}
msg = msg + x + "\n";
}
alert(msg);
</script>
0 2 4 6 8 10 12 14 16 18 20
<script>
var msg = "";
for (var x = 0; x <=20; x++)
{
if (x%2)
msg = msg + x + "\n";
}
alert(msg);
</script>
Output:
1 3 5 7 9 11 13 15 17 19
Similarly, break is employed to stop loop iterations completely.
Ex:
<script>
var msg = "";
var t = 1;
while (t <= 10)
{
if (t == 8)
{
break;
}
msg = msg + t + "\n";
t++;
}
alert(msg);
</script>
Output:
1 2 3 4 5 6 7
Assignment
1- In the code below, which numbers are displayed in the alert box?
var msg = "";
for (var x = 0; x < 10; x++)
{
if (x == 5 || x == 7)
{
continue;
}
msg = msg + x + "\n";
}
alert(msg);
</script>
2- How can you display the odd numbers between 1 to 20 WITHOUT
the use of continue?
Possible Answers
0, 1, 2, 3, 4, 6, 8 and 9.
for (var x = 1; x <= 20; x = x + 2)
{
msg = msg + x + "\n";
}
alert(msg);
var msg = "";
var x = 1;
while (x <= 20)
{
msg = msg + x + "\n";
x = x + 2;
}
alert(msg);