Loops are a way of repeating the same block of code over and over. There are two types of commands for looping. For and While.
While :
A while loop repeats a block of code while a condition is true. Like an if statement, the condition is found in parentheses.
Example :
var a = 1;
while (a < 10) {
alert(a);
a = a+ 1;
}
// i is now 10
For :
A for loop is similar to an if statement, but it combines three semicolon-separated pieces information between the parentheses: initialization, condition and a final expression.
The initialization part is for creating a variable to let you track how far through the loop you are - like i in the while example; the condition is where the looping logic goes - the same as the condition in the while example; and the final expression is run at the end of every loop.
Example:
for (var z = 1; z < 10; z++) {
alert(z);
}
This gives us alert boxes containing the numbers 1 to 10 in order.
By the way, z++ is equivalent to z = z + 1
No comments:
Post a Comment