FOR LOOPS
A for loop includes the following three components:
- initialization
- test condition
- increment/decrement
For example:
for (i=0; i<=10; i++) {
document.write("i = : " + i + "<br>");
}
In this case,
- initalization: i = 0
- test condition: i <= 10
- increment: i++
A while loop is really a reformulation of a for
loop. It includes a test condition and a counter (iterator). The loop
continues as long as the test condition is true.
You can reformulate the previous for loop as a
while loop, as shown in the following code:
i=0;
while (i <= 10){
i++;
document.write("i = : " + i + "<br>");
}
In this case,
- initalization: i = 0 -- this is done before the loop starts
- test condition: i <= 10 -- the loop continues as long as this is true
- increment: i++ -- occurs within the code block of the loop
Moving On
In this lesson, you learned more about using strings and numbers. You also
learned how to create three types of flow control statements
(if, if/else, if/else-if/else). In
addition, you found about while and for loops to
repeat blocks of code as long as certain conditions are met.
In the Lesson 5, you learn add a date and time to your pages automatically, and how to create a timer so that scripts execute only after a certain amount of time has elapsed.
Before you move on, don't forget to do the assignment and take the quiz. In addition, visit the Message Board to share questions, solutions, and experiences with your fellow students.
