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 code.
Using a loop simplifies the process.

loop

The format for the loop is as follow:

for (initial-counter; test condition; increment counter)
{ statements; }

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.

Example:
YouTube - Javascript Loop Example
Full Screen Full Screen

while loop

In a while loop, statements are executed over and over until the condition fails.
Below is the format.

while(condition) { statements; }


Below is an example
In this while loop 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.

var i = 0; while(i < 10)
{ document.writeln("Inside loop number " + i + "<br>"); i++; }




do-while loop

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.

do { statements; } while (condition)

Below is an example of the do-while loop.

var i = 1; do
{ document.writeln("Inside loop number " + i + "<br>");
i++; } while (i < 11)





break and continue

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.

var i; for (i = 1; i < 11; i++)
{ if (i == 5) { break; }
document.writeln("Inside loop number " + i + "<br>"); }
document.writeln("You have jumped out of the loop.");

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).

var i = 1; while(i < 11)
{ if (i%2 == 0)
{ document.writeln("You have skipped loop " + i + "<br>"); i++; continue; }
document.writeln("Inside loop number " + i + "<br>"); i++; }






Intro         Variables         Statements         If then else

Loops         Objects         Functions