Web Design Specialists. |
Javascript Loops
|
|
Suppose you wanted to perform a statement or series of statements 10 times. You could write
these statements 10 times over, but this makes for very long, cumbersome code. Using a loop
simplifies the process.
for loop
The format for the for loop is as follow:
A counter is what keeps track of how many times the loop has executed. The initial-counter is set one time. The test condition is used to test the value of the counter each time before entering the loop. The counter is incremented one each time the loop has completed. Below is an example. The writeln statement will execute a total of 10 times.
Variable i is the counter used and it is initialized to 1. A test is made to make sure that i is less than 11. The writeln is executed and then i is incremented by 1. Another test is made for less than 11, the writeln is executed, i is incremented, and so on.
In a while loop, statements are executed over and over until the condition fails.
Below is the format.
Below is an example you can test. In this example, the counter variable i is initialized to 0. Before the statements in the loop are executed, the condition must be true. If so, the writeln is executed and i is incremented. The statements continue to be executed until the condition fails.
A do-while loop is very similar to the while loop. The main difference is that all the
statements in the loop are executed at least once, where the while loop performs the
condition test first. The do-while loop tests the condition last. Just like the while loop,
the statements continue to execute until the condition returns a false.
Below is an example of the do-while loop.
Break and continue are methods of escaping out of a loop. Below is an example of a
break from within a loop. When a break is made, you jump completely
out of the loop and continue with the next statement after the loop. This example jumps out
of the loop when the counter is equal to 5.
Below is a demonstration of a continue.
When a continue is made, you only jump out of the current
loop but return to the condition at the beginning of the loop. This example terminates any
loops where the counter is an even number (divisible by 2).
|
Intro
|
Variables
|
Statements
|
If then else
|
Loops
|
Objects
|
Functions