Fortunately, JavaScript can perform repetitive operations, also known as "loops". Loops are a set of instructions
that are used to repeat the same block of code until a specific condition is
met. JavaScript allows for the use of two types of loop statements, For and
While. In many cases, you control the loop process by using a counter that
either increments or decrements with each cycle of the loop. The For loop
is most appropriate when you want to perform a specific number of loops through
the block of code, by way of the counter. On the other hand, use the While loop
when you do have an undetermined number of times you need to loop. The While
loop will end once the condition is met.
For Loop
The For loop is executed until a specified condition returns false. Here is the sytnax you would use for a For loop.
for (initial value; condition; increment/decrement)
{
JavaScript Block of Code
}
|
Let's take a look at an example of how to use the For loop. In this
example, we will write the numbers 1-10 on the screen.
<script type="text/javascript">
var x = 0;
for (x = 0; x <= 10; x++)
{
document.write(x + "<br />");
}
</script> |
In this example, the initial value of the variable x is zero. As the loop cycles, the value of x increments by one. When the value reach eleven, the condition is false and the loop terminates.
While Loop
The while loop is used when you need to loop through the block until a specific condition evaluates to true. As long as the condition produces a false
result, the loop cycle continues. Here is an example of the While loop syntax:
while (condition)
{
JavaScript Block of Code
}
|
Let's take a look at an example of how to use the While loop. In this
example, we will write the numbers 1-10 on the screen.
<script type="text/javascript">
var x = 0;
while (x <= 10)
{
document.write(x + "<br />");x++;
}
</script> |
While you may notice that we produced the same results as we did using the For loop. In this example, we were able to accomplish the same result by using the
While loop. For and While loops are very important tools in the JavaScript developer's toolbox.
Did you find the page informational and useful? Share it using one of your favorite social sites.
Recommended Books & Training Resources