The first example, loopexec, demonstrates the execution of a
loop line by line. The example consists of three main areas: the
code box on the left, the explanation on the right, and the
variable watch on the bottom. The code box features the executing
script, with the next line of code to be executed highlighted.
The explanation box on the right will gives a short explanation
of the code and the program state. Below the code box is a
variable watch for the counter variable. It will alway contains
the current value of the counter variable.
See the example.
The next two examples are simple examples of looping
statements. The first example is a while loop that prints the
numbers 1 to 20 on the screen. The second example is the same,
except that a for loop is used in place of the while loop. As
with all of the examples, make sure that you not only look at the
source, but click on the links to the analysis.
While loop example and source.
For loop example and source.
This example is my tribute to Thomas Dolby, called blind.htm. If it were rewritten, it could conceivably be used in a Web page, but as it is, its primary raison d'etre is to illustrate a potential use of loops. The code loops through two 'if' statements that toggle the foreground and background colours between black and white, while displaying text on the screen.
WARNING! This example features a rapidly flashing screen that
could trigger an epileptic seizure. If you have epilepsy, it is
not advised that you execute this code.
See the example,
or view the source.
Cont.htm is a script that illustrates the use of the continue
statement. It is nearly identical to the for loop example, with
the addition of a continue statement to skip printing the number
13 to the screen.
See the example,
or view the source.
This example illustrates the use of the break statement. The
page is an interactive graffiti wall that lets you dynamically
add your own graffiti. The code utilises the break statement to
exit from an infinite loop. Check it out.
See the example,
or view the source.
Next is a example to demonstrate how to use arrays. The
scripting behind the example is fairly simple, but it is good to
look at before moving on to the next example. The code creates an
array with four elements and assigns string values to each
element. The script then displays the content of two of the
variables.
See the example
or view the source.
This final example illustrates a more plausible use of arrays.
Although a fully functional program would be difficult - not to
mention impractical - to implement in JavaScript, the example
illustrates the use of loops and arrays well. The code simulates
a simple address book. It asks the user how many entries they
would like to enter, and then asks for each person's first name,
last name and phone number. Once the user is finished entering the
data, the script displays all of the entries on the screen.
See the example,
or view the source.