Loops repeat a code block. They can repeat for a definite or indefinite number of times. Much like English grammar
Perform a code block for a set number times.
Perform a code for a set number times with a counter provided.
Syntax:
var max_count = 10
for (var i=0; i<max_count; i++) {
}
The definition of a for loop is actually three distinct statements on one line. Statements can be separated with ;
when not separated by blank lines.
First, we define a counter variable var i=0
. We create a local variable with var
because i
is only applicable in this loop.
Second, we add a condition to end the loop. As long as i<max_count
, the code block inside the loop will run.
Finally, we modify our counter variable at the end of each iteration, i++
.
Perform a code block while a condition is met.
Another use of
Why do we use i
for the default counter variable?