Did you find this useful?
Socialize it today.


JavaScript For and While Loops

Thursday, April 12, 2012

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.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

Murachs JavaScript and DOM Scripting Professional JavaScript for Web Developers HTML CSS and JavaScript Editor