Javascript for Loop
Javascript for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
Explanation: The example below defines a Javascript for loop that starts with i=0. The Javascript for loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
There are four important aspects of a Javascript for loop:
The counter variable is something that is created and usually used only in the for loop to count how many times the for loop has looped.
The conditional statement that decides whether the for loop continues executing or not. This check usually includes the counter variable in some way.
The counter variable is incremented after every loop in the increment section of the for loop.
The code that is executed for each loop through the for loop.
This may seem strange, but 1-3 all occur on the same line of code. This is because the Javascript 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.
|