The JavaScript For Loop resembles the for loop you may have seen in many other programming languages. It is used when you need to do a set of operations many times, with an increment of some kind after each run through the block of code.
If you have read the previous lesson JavaScript While Lesson then this should be a cinch.
There are four important aspects of a JavaScript for loop:
This may seem strange, but 1-3 all occur on the same line of code. This is because the for loop is such a standardized programming practice that the designers felt they might as well save some space and clutter when creating the for loop.
This example will show you how to create a simple for loop that prints out the value of our counter until the counter reaches 5. Pay special close attention to the three different items that are on the first line of the for loop code. These are the important for loop parts 1-3 that we talked about earlier.
<script type="text/javascript">
<!--
var linebreak = "<br />";
document.write("For loop code is beginning");
document.write(linebreak);
for(i = 0; i < 5; i++){
document.write("Counter i = " + i);
document.write(linebreak);
}
document.write("For loop code is finished!");
</script>
The counter variable name i may seem a little strange, but it has been used for years now! No matter the language, i is the default name for a loop counter. Other common variable names are j, k, x, y and z.
In this example, our counter was initially set to 0 with "i = 0;" and then the conditional statement "i < 5;" was executed. Our counter was indeed smaller than 5, so the for loop's code was executed.
After the loop's code is executed then the increment "i++" happens, making the counter i equal to 1. The for loop then checked that i was less than 5, which it was, causing the for loop's code to be executed again.
This looping happened a couple more times until i was equal to 5, which is not less than 5, causing the for loop's code to stop executing.
For loops may seem very confusing at first, but let me assure you, they are quite useful and should be studied thoroughly by anyone who wishes to become an intermediate programmer.
Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!
2003-2008 Erack Network | Copyright | Privacy Policy | Advertising Information
Site design by Seattle Web Design