Let’s look at some more examples of using for loops.
The update statement portion of for loops creates lots of flexibility for how data, and the progression of the for loop can occur.
So far, we have only discussed and seen this statement utilize the increment by 1 syntax (i.e i++
). But, any statement that returns a new value for the defined variable may be used. This might include any of the following;
i++;
i--;
i+=2;
i-=2;
i = (i ** 10) / 3;
As long as the update statement returns a valid Number, then anything can be used. NOTE: The only thing to be wary of is that the update statement moves the Number variable towards completion of the loop. Be cautious of update statements that cause an infinite loop. That is, statements that do not move the Number variable towards completion of the for loop. As this will result in your code locking up and breaking. For example, the following would cause a silent problem, as the Number variable is decreasing in the update statement, but the conditional statement will only cause an exit once the Number variable is greater than 10.
for( let i=5; i < 10; i-- ) {
// do something
// never exits this loop
}
On the other hand, the following example increments by 60 every loop, until i
is greater than 400. Notice how the diagonal lines are each 60 pixels apart? This is because of the update statement’s use of increment by 60.
{ TODO: } Change the update statement’s value from 60 to some other values to see how the sketch changes.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |
The first statement of a for loop is the Number variable declaration and initialization. As mentioned on the previous page, this tells the for loop what variable to use and what it is initially set to. This value can be initialized to any Number. It is common to see it, or set it to 0, but, this is not a limitation.
Likewise, you will see the variable i
often used in for loops, but any variable, following the rules described in variable naming can be used.
In the below example, the declaration statement initializes the value x
to 20. This is used to start drawing diagonal lines at 20px on the X-axis.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |
As has been shown, but should be highlighted, the variable used in for loops is scoped such that it can be used within the function block of the for loop. In the below example, the Number variable i
is initialized to the value of 20. This variable is used to draw sets of connected lines, whose angles get progressively more ‘severe’. This is accomplished by multiplying the variable i
by 1.5 at the “connection point”.There by creating larger value of difference between the starting point (i
) and the connection point (i*1.5
).
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |