HTML and CSS Reference
In-Depth Information
reviewed the advanced methods on the array object that use callbacks. There, the iterative
flow control was built into the various array methods. In this section, you'll examine the native
iterative control statements, including for and while loops.
Using the for loop
The for loop is useful in cases in which a block of code should run based on a deterministic
number of items. In some cases, you might want to iterate over a list of items in an array
or list; in other cases, you might want to run a block of code a specific number of times to
perform some type of animation or to create a specific number of objects.
The syntax of the for loop is as follows:
for(< counter >;< expression >;< counter increment >)
< code to run >
The for loop needs three elements: a counter, an expression, and an increment.
The counter variable holds the current number of times the loop has run. You need to
initialize the counter appropriately, such as to 1 or 0.
The expression element evaluates the counter against some other value. Its purpose is
to set a limit to the number of times the for loop runs. For example, if you wanted the
loop to run 10 times, you could initialize the counter to 0, and the expression would be
counter < 10. Doing so would ensure that the loop would run only while the expres-
sion returns true, that is, while the counter variable is less than 10. As soon as the
counter equals 10, loop processing would stop, and code processing would continue
after the for loop.
With the counter increment , the for loop must be told how to adjust the counter vari-
able after each loop iteration. The increment can be positive or negative depending on
how the loop is set up. You can set the increment so that the loop counts sequentially,
or use mathematical operators to increment by a different value.
The code or body of the loop is a block of code surrounded by curly braces. This code
section runs for each loop iteration. The following code samples demonstrate various ways to
use a for loop.
First, here's a simple for loop that runs a block of code 10 times:
for (var i = 0; i < 10; i++) {
Notice that because the counter is starting at 0, the expression is to be less than 10. If the
counter is to start at 1, the expression would be <= 10. This is important to keep an eye on.
The counter increment uses the addition shorthand ++ to increase the counter by one on
each iteration. The following code goes in the reverse order:
for (var i = 10; i > 0; i--) {
Search WWH ::

Custom Search