We've seen that while loops have different variants. This chapter will introduce another popular loop called A For loop.
For loop
The For loop is the most compact form of the loop and consists of the following three important parts:
- The initial value of the loop initialization counter. Before the initialization statement execution loop begins.
- A test statement that tests if a given condition is true or false. If the condition is true, the code given in the loop that will be executed, otherwise the loop exits.
- Loop statement, you can increase or decrease the counter.
You can separate the lines in all three sections with semicolons.
Grammar
for (initialization. test condition; Iteration statement) {
statement (s) to was executed if test condition is true
}
Example:
The following example illustrates a basic for loop:
<script type= "Text/javascript" >
<!--
var count;
document.write ("Starting Loop" + "<br/>");
for (count = 0, Count < count++) {
document.write ("Current count:" + count);
document.write ("<br/>");
}
document.write ("Loop stopped!");
-->
</script>
This produces the following result, similar to the while loop:
Starting Loop current
count:0 current count:1 current count:2 current
-count:3 current
Count: 4 Current
count:5 current Count:6 current Count:7 current Count:8 current
count:9
Loop stopped!