When you want to do something more than once a loop might help.  If you did PHP you saw while loops already.  However, for loops work a bit differently as they are designed to do something a set number of times. 

Create a new page and call it for.html.  Create a function called forloop with this inside:

for (var i=1;i<=10;i=i+1) {

Put an onload event trigger in the opening body tag.  Try the page and you should get ten alerts.  That is because of the code inside the normal brackets above.  This is what that code does:

  1. first a variable called i is set to 1 (i is often used as a name for the counter in loops)
  2. after the semi-colon the limit for i is set (here i must be less than or equal to 10) this check is done at the start of each run through the loop
  3. the final chunk sets the way in which i changes each time through the loop (here it goes up by 1)
  4. the code to run each time through the loop is grouped inside the curly brackets/braces

The sequence will be:

  1. first time through i is 1 which is less than 10 so the code inside the brackets is run
  2. once the code inside the loop is finished i is incremented (increased) by 1 as instructed so that it is now 2
  3. the browser JavaScript engine now goes back to the start of the loop and checks the condition again and finds that 2 is still less than 10 so runs the code
  4. this is repeated until i is 10 and still the code runs again
  5. the next time the loop starts i is 11 so the test fails and the code is not run

The conditions inside the normal brackets can do many things:


Showing a series of images in a loop.  Moving things around the page gradually.  Fading items in and out of a page gradually.  Going through data in an array of known size.