How to Use the for Loop in JavaScript, and how to use javascript
As we can see, the while loop has different variants. This chapter introduces another popular loop called for loop.
For Loop
A for Loop is the most compact form of a loop and consists of the following three important parts:
- The initial value of the counter. Before the initialization statement execution cycle starts.
- Test statement to test whether the given condition is true or false. If the condition is true, the code given in the loop to be executed will exit.
- Loop statement, which can increase or decrease the counter.
One row in all three parts can be separated by a semicolon.
Syntax
for (initialization; test condition; iteration statement){ Statement(s) to be executed if test condition is true}
Example:
The following example shows a basic for loop:
<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>
This produces the following results, which are similar to the while loop:
Starting LoopCurrent Count : 0Current Count : 1Current Count : 2Current Count : 3Current Count : 4Current Count : 5Current Count : 6Current Count : 7Current Count : 8Current Count : 9Loop stopped!