For LoopsS2C Home « For Loops
In this lesson we look at the for
loop statement which is generally used for repeating some statements a set numer of times. The
for
statement is more compact than the while
statement
and we can apply variables to the loop within the for
statement itself.
The for
Statement
The for
statement will loop through a section of code a set number of times. The for
statement contains three parts. In the first part we initialize
a counter variable with a value, this only happens on initial entry to the for
loop. The second part is a condition which tests the variable value at the start of
each loop and if the condition is no longer true the for
loop is exited. The final part of the for
statement is an expression to be evaluated at the end of each iteration of the loop. This normally takes the form of a counter that is decremented or incremented.
Following are examples of the for
loop statement which increment and decrement the expression variable.
// execute the loop until loop condition is false.
for (var i=0; i<3; i++) {
alert('The i variable is = ' + i);
}
alert('left first for loop');
// execute the loop until loop condition is false.
for (var i=10; i>9; i--) {
alert('The i variable is = ' + i);
}
alert('left second for loop');
The break
Statement
The break
statement allows us to terminate the current loop or label
statement. Execution is passed to the statement following the current loop or
label
statement.
// execute the loop until break.
for (var i=0; i<4; i++) {
if (i == 2) {
break;
}
alert('The i variable is = ' + i);
}
alert('left for loop');
The continue
Statement
The continue
statement allows us to continue from the expression part of the loop or from a predefined
label
statement of a labelled loop.
// execute the loop until loop condition is false.
for (var i=1; i<4; i++) {
if (i == 2) {
continue;
}
alert('The i variable is = ' + i);
}
alert('left for loop');
The label
Statement
The label
statement allows to insert a statement identifier we can refer to from a break
or
continue
statement.
// execute the loop until loop condition is false.
for (var i=1; i<3; i++) {
atLabel:
for (var k=1; k<3; k++) {
if (k == 2) {
continue atLabel;
}
alert('The i variable is = ' + i + ' and k variable is = ' + k);
}
}
alert('left for loop');
Reviewing The Code
We used the for
statement with an increment and decrement counter and with the break
,
continue
and label
statements.
Lesson 5 Complete
In this lesson we looked at the for
loop statement.
Related Tutorials
JavaScript Intermediate Tutorials - Lesson 4 - While and Do....While Loops
What's Next?
In the next lesson we take a look some more maths functions.
JavaScript Reference
for
statement
break
statement
continue
statement
label
statement