Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
First posted :
03/24/2008
Times viewed :
445
JavaScript Loops
Introduction
Loops can be used to repeat something again and again till a
condition returns false or true depending on how you need it. Lets imagine a
loop in a real life. Lets say I drive to an airport to pick up my friend. After
receiving at the gate (still in my car) I see that he isn’t outside till yet,
so I drive around the terminal (to save parking fees). After receiving for the
second time at the gate, I check again for the condition if he is outside. If
he is again not there then I will drive again around the terminal. I repeat
this until he comes out of the gate. There are three types of loops: do…while,
while and for loop. The following examples show each loop:
do … while loop
The do…while loop can be used till a condition returns false.
It looks like this:
do{
// do
something here
} while (condition)
This loop runs one time in any case, whether the condition
is true or false. After that it will check for the condition.
Example of do … while loop
<html>
<head>
<script type="text/javascript">
var i = 0
do
{
i++
document.write(i+"<br>")
}while(i<10)
</script>
</head>
<body></body>
</html>
Output
while loop
The while loop is executed as long as a condition is true.
It has the following syntax:
While (condition)
{
// do something
here
}
Example of while loop
<html>
<head>
<script type="text/javascript">
var i = 0
while(i<10)
{
i++
document.write(i+"<br>")
}
</script>
</head>
<body></body>
</html>
Output
For loop
A for loop is executed till a condition returns false. It
has basically the same syntax then in other languages. It takes 3 arguments and
looks like this: