Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML

Print Version

JavaScript For Loop

We learned in the previous lesson that "loops" enable your program to continuously execute a block of code for a given number of times, or while a given condition is true.

In that lesson, we saw that the While loop executes code while a condition is true.

In this lesson, we will see that the JavaScript For loop executes code for a specified number of times.

Therefore, we could rewrite the example from the previous lesson to use a for loop.

Example For statement:

<script type="text/javascript">
<!--
var myBankBalance = 0;

for (myBankBalance = 0; myBankBalance <= 10; myBankBalance++)
{
document.write("My bank balance is $" + myBankBalance + "
"); }
//--> </script>

The resulting output:

Exlanation of code

  1. We started by declaring a variable called "myBankBalance" and setting it to 0
  2. We then opened a for loop with our condition between brackets. Our condition sets a value to our variable, checks if the current value of the variable is less than or equal to 10, then increments the value by 1.
  3. This is followed by code to execute while the condition is true. In this case, we are simply, outputting the current value of myBankBalance, preceded by some text. This code is placed within curly braces.
  4. When the browser reaches the closing curly brace, if the condition is still true, it goes back to the first curly brace and executes the code again. Of course, by now, the myBankBalance variable has been incremented by 1. If the condition is not true (i.e. the variable is greater than 10), it exits from the loop.

Enjoy this website?

  • Share
  • Add this page to your Favorites
  • Link to this page (copy/paste into your own website or blog):
  • Link to Quackit using one of these banner ads.
  • Help support Quackit by making a donation

Oh, and thank you for supporting Quackit!

© Copyright 2000 - 2010 Quackit.com