The easiest form of a loop is the for statement. This one has a syntax that is similar to an if statement, but with more options:
for(condition; end condition; change){
// do it, do it now
}
Lets for example see how to execute the same code ten-times using a for
loop:
for(var i = 0; i < 10; i = i + 1){
// do this code ten-times
}
Note:
i = i + 1
can be writteni++
.
While Loops repetitively execute a block of code as long as a specified condition is true.
while(condition){
// do it as long as condition is true
}
For example, the loop in this example will repetitively execute its block of code as long as the variable i is less than 5:
var i = 0, x = "";
while (i < 5) {
x = x + "The number is " + i;
i++;
}
The Do/While Loop is a variant of the while loop. This loop will execute the code block once before checking if the condition is true. It then repeats the loop as long as the condition is true:
do {
// code block to be executed
} while (condition);
Note: Be careful to avoid infinite looping if the condition is always true!
The do...while statement creates a loop that executes a specified statement until the test condition evaluates to be false. The condition is evaluated after executing the statement. Syntax for do... while is
do{
// statement
}
while(expression) ;
Lets for example see how to print numbers less than 10 using do...while
loop:
var i = 0;
do {
document.write(i + " ");
i++; // incrementing i by 1
} while (i < 10);
Note:
i = i + 1
can be writteni++
.
Loops are repetitive conditions where one variable in the loop changes. Loops are handy, if you want to run the same code over and over again, each time with a different value.
Instead of writing:
doThing(cars[0]);
doThing(cars[1]);
doThing(cars[2]);
doThing(cars[3]);
doThing(cars[4]);
You can write:
for (var i=0; i < cars.length; i++) {
doThing(cars[i]);
}