FOR loops will run the same code a set number of times:
for (var i=1;i<=10;i=i+1) {
alert(i);
}
This will run the code ten times. It looks a bit scary until you understand each bit. In the brackets are the three pieces of information which cause the loop to run 10 times:
- first i it is set to 1 (i is often used as the counter in loops)
- after the semi-colon the limit for i is set (here i must be less than or equal to 10) - this check is done at the start of each run through the loop
- the final chunk sets the way in which i changes each time through the loop (here it goes up by 1)
- the code to run is grouped inside curly brackets
The sequence will be:
- first time through i has been set to 1 which is less than 10 so the code runs
- i is incremented (increased) by 1 to 2 and is still less than 10
- this goes on until i is 10 and so the code runs again
- the next time the loop starts i is 11 so the test fails and the code is not run
One use of the FOR loop would be to run through a JavaScript array:
var fred=new Array('chicken','beef','pork','vegetarian');
for (var i=0;i<=3;i=i+1) {
alert(fred[i]);
}
You can increment (or decrement) by any amount and start with any value for the counter. All of these are valid:
for (var i=100;i>0;i=i-1) {
for (var i=1;i<30;i=i*2) {
for (var i=100;i>0;i=i-10) {
for (var i=0;i<30;i=i+8) {
for (var i=1;i<=10;i++) {
The second one multiplies i by 2. The last example is identical to the original example above. Both i++ and i=i+1 increment i by 1 each time.




