JavaScript FOR loops

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:

The sequence will be:

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.

submit to reddit Delicious Tweet