{{{{ JavaScript - Loops }}}}

Simple Loop - for
Double Loop
Conditional Loop - while
Example - mosaic
Start of website

Alphabetical index

Summary of colours in code: green is HTML useful for JavaScript, red is JavaScript, blue is a name and everything else is grey.



Simple loop - for

When writing a program, you often find that you want to write a lot of statements that are the same, or very similar. It seems a waste of time to keep repeating yourself, and yes, there is an easier way to do it. In the code below, you enter a number and it writes out a multiplication table for that number. It uses dynamic HTML to do this, as it writes it when you type something in and click on the button, which is after the webpage has been loaded. It can't set up the lines one at a time. So it sets a variable "outp" as empty, then gradually builds up an HTML string by adding to the end of it. Note that the <BR> is just a literal here, although when it gets actioned as HTML it will create a new line. Finally the code outputs the whole string to the output HTML.

The code for actually working out the times table is inside the for. You can see that the statements following for start with {, are indented (extra spaces in front) and end with }. As with if, it is the { ... } which defines the contents of the for loop to the computer, while the spaces are for you and me to make it easier to understand. The for statement has complicated stuff just after it in round brackets (...), again just like the if statement, but this time it is more than just a simple (or even complicated!) condition. There are three parts to it, with semi-colons ";" between each part. The first bit starts the loop, the second ends the loop, the third says what happens during the loop (yeah - really logical!) This particular example says Anyone who's coded loops in other programming languages didn't bother to read that, I hope! They all do it roughly the same, even if they write it different ways.

Enter number
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Multiplication table

function timtab() {
  var prod = document.times.mult.value
  var outp = ""
  for (i = 1; i <= 12; i++) {
    ans = i * prod
    outp = outp + i + " x " + prod + " = " + ans + "<BR>"
  }
  document.getElementById('outtab').innerHTML = outp
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME=times>
Enter number
<INPUT TYPE=TEXT NAME=mult SIZE=4>
<INPUT TYPE=BUTTON VALUE="Generate table" ONCLICK="timtab()">
</FORM>
<BR><SPAN ID="outtab"></SPAN>
</BODY>
</HTML>

If you're interested, I've used "i" for a variable for reasons going back practically to pre-historical times for programming. Fortran defined by default I, J, K, and L as integers (whole numbers) rather than reals, so I've carried on doing it. You don't have to! However, it is quite useful to have certain variable names that you always use for certain purposes, since it makes it easier to understand the program, and easier to type! You could try to invent "meaningful" variable names each time, but it gets difficult for all these loop counters.



Double loop

You can also have one loop inside another. That means for each pass of the outer loop, you do the entire of the inner loop. Multiple loops can get rather involved, so here it becomes even more important that you put extra spaces in front for each loop, so you can disentangle one from the other - and don't forget all the { and particularly the }s! In this example, the outer loop uses "i" as a loop counter, and "j" is used by the inner loop. I could have made a square multiplication table, but since 7 x 8 is the same as 8 x 7, I thought making a triangular table would be more interesting. You can see that I have used "i" as part of the condition for the end of the inner, "j", loop.

I have used document.write to set up the table, since the table is being written out while the webpage is being loaded. Since it is important that the numbers line up, I've set out the figures in a HTML table. This means that I need to generate all the <TR>s and <TD>s in the right place! I have also had to break up the </TD>s, </TR>s and </TABLE>, as the HTML checker objects if I don't.

<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Multiplication table

function tab() {
  document.write ("<TABLE>")
  for (i = 1; i <= 12; i++) {
    document.write ("<TR>")
    for (j = 1; j <= i; j++) {
      ans = i * j
      document.write ("<TD>" + ans + "</" + "TD>")
    }
    document.write ("</" + "TR>")
  }
  document.write ("</" + "TABLE>")
}
</SCRIPT>

</HEAD>
<BODY>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
tab()
</SCRIPT>

</BODY>
</HTML>




Conditional Loop - while

The previous loops were fixed loops. They happened a definite number of times (even if that number was a variable). In JavaScript, like other programming languages, you can have a loop which repeats while a certain condition is met, and doesn't end until the condition fails. In the example below, the code calculates how long it takes for your savings to double in value for a given interest rate. You input the interest rate, which is picked up by the code in the usual way. The code sets up the savings that we are working on, which are set to the value one. I also set up the 'years' variable to start at the value zero. Now for the loop. This uses while. You may notice that it's a lot simpler than the for loop, with just a simple condition, looking rather like an if statement, in fact. Anyway, "tot" is less than 2 (being equal to 1) and so we enter the while loop, which is set up in the normal way, with {...}. The first year's interest is calculated and added to "tot". I also add 1 to "years", so I can count how many years I've done so far. On meeting the }, the code returns to the while condition, and sees if "tot" is still less than 2, that is, has it doubled yet? This is unlikely (unless you choose an interest rate of 100% or more!), so it calculates another year, and ups the "years" counter again, and loops back to check the condition again.. Finally, "tot" will have doubled, so we drop out of the loop, to the next statement. This sets up the output text box to contain the "years" value.

Enter interest %



Savings double in years
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Calculate interest until total doubles

function compound() {
  var rate = document.comp.intr.value
  var tot = 1.00
  var years = 0

  while (tot < 2) {
    tot = tot + (tot*rate/100)
    years++
  }

  document.comp.doub.value = years
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME=comp>
Enter interest %
<BR><BR><INPUT TYPE=TEXT NAME=intr SIZE=4>
<BR><BR><INPUT TYPE=BUTTON VALUE="How long to double?" ONCLICK="compound()">
</FORM>
<BR><BR><INPUT TYPE=TEXT NAME=doub SIZE=3 DISABLED> years
</BODY>
</HTML>

One problem with while loops is that you don't set up a counter in the statement itself, with an initial value and an increment. Here I have to set up my own counter of "years", and remember to initialise it, and to add one to it (and believe me, I've forgotten to do either on occasion!) There is another, more important problem. for loops operate for a fixed number of times (unless you do someting silly like set up the final condition to be less than the initial condtion, or subtract the counter rather than adding it). while loops, however, will repeat for ever if the condition is always true. In this example, if you input a negative interest rate (which means that interest is subtracted from your savings rather than being added to it!), then your savings will never double. So what happens? In some computer languages, the code does loop round for ever, and this is called an infinite loop. (Obviously, there will be some way to stop it, if only by turning off the computer!) In webpages, the browser should stop the script after a time, and ask if you want to cancel it. However, it's best not to have infinite loops, so watch the condition. In this example, you could provide a safeguard by making a condition of (tot < 2 && years < 100), as then the loop will only repeat 100 times maximum. But then you would need to make an error message if "years" reached 100.

In fact, you could code JavaScript without using for at all, since you can always use while and set up and test your own counter. You may prefer this if you find the format of for conditions a little messy. Do be careful of infinite loops, though! Make sure that you increment your loop counter, or change whatever you're testing in the condition. (It must be pointed out that it is possible to have an infinite loop with a while statement, if you test for a condition which is always true. But it's less likely.)



Example - Mosaic

The example below only uses techniques that we've already covered. It produces a surprisingly interesting webpage for such simple code (although you might not agree!)

The HTML is extremely simple. The trick of this code is the setting up of the mosaic and palette of colours. The first element of the mosaic is defined like this:

<IMG SRC='col0.gif' ALT=' ' NAME='row1col1' ONMOUSEDOWN=changemos(1,1)>

"col0.gif" is a picture file which is plain white. The image is given the NAME of "row1col1", and if you click on it, the code of "changemos(1,1)" is actioned. However, there are 100 of these elements, and every element has a different name, and calls "changemos" with different values. You could code each one separately, but what a lot of code! So I set up loops to do this, using document.write (you can't do loops in normal HTML). I've made the setting up of the mosaic elements in the <HEAD> ... <HEAD> as a function, and called this in the <BODY>...<BODY>, but if you prefer, you could put the code directly within the <BODY>...<BODY> - but within <SCRIPT>...<SCRIPT> of course. I've made the contents of the document.write grey in my colour code rather than the HTML colours, since it really it a literal rather than HTML at this stage. It only gets actioned as HTML when the page gets loaded. Making it grey allows me to shows how you can build up a string of HTML with variables in it, so enabling me to produce all 100 elements, each with its own unique NAME and call to "changemos" - very clever!

If you look further down, you'll see what "changemos(i,j)" does. It sets that particular element of the mosaic to a picture file called "colN.gif", where N is the value of the variable "col". There are nine of these "colN.gif" files, each one a different colour. This is a global variable, defined at the start of the JavaScript. It has to be a global variable, because it gets set by one function and used by another. A local variable would only work within one call of one function.

There is a similar set up of the colour palette. This time, there doesn't have to be a NAME, since I don't need to alter these images. But I do need to do something if you click on it - I need to alter the variable "col"! I also change a separate picture file, just so you can see what the current colour is. The other difference between the mosaic and the colour palette is that every element of the mosaic starts off as the same colour, and so the same file. But the colour elements need to be different files. You can see how this is done below.

The last function is called by the button, and it clears the mosaic down if you want to make a new picture. Since I have already defined a function which changes the colour, and a function which sets a mosaic element, I can use both these to clear down the mosaic.

This is not too long a program, but even so, I did not try to code it all in one go. I wrote one function, tested that (found a mistake or two!) and then wrote the next, and so on. That's the way to write programs!

Current colour - Click in squares

<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Global variables

col = 1

// Set up mosaic

function setmos() {
  document.write ("<TABLE BORDER>")
  for (i = 1; i <= 10; i++) {
    document.write ("<TR>")
    for (j = 1; j <= 10; j++) {
      document.write ("<TD>")
      document.write ("<IMG SRC='col0.gif' ALT=' ' ")
      document.write ("NAME='row" + i + "col" + j + "'")
      document.write (" ONMOUSEDOWN=changemos(" + i + "," + j + ")>")
      document.write ("</" + "TD>")
    }
    document.write ("</" + "TR>")
  }
  document.write ("</" + "TABLE><BR>")
}

// Set up colours

function setcol() {
  document.write ("<TABLE BORDER><TR><TD>")
  for (k = 0; k <= 8; k++) {
    document.write ("<IMG SRC='col" + k + ".gif' ALT=' ' ")
    document.write (" ONMOUSEDOWN=changecol(" + k + ")>")
  }
  document.write ("</" + "TD>" + "</" + "TR>" + "</" + "TABLE>")
}

// Change a mosaic tile

function changemos(i,j) {
  document.images['row' + i + 'col' + j].src = 'col' + col + '.gif'
}

// Change colour

function changecol(k) {
  col = k
  document.images['currcol'].src = 'col' + k + '.gif'
}

// Clear whole mosaic

function clmos() {
  changecol(0)
  for (i = 1; i <= 10; i++) {
    for (j = 1; j <= 10; j++) {
      changemos(i,j)
    }
  }
  changecol(1)
}

</SCRIPT>

</HEAD>
<BODY>
<IMG SRC='col1.gif' ALT=' ' NAME='currcol' ALIGN=LEFT>
Current colour - Click in squares<BR><BR>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
  setmos()
  setcol()

</SCRIPT>
<INPUT TYPE=BUTTON VALUE="Clear" ONCLICK="clmos()">
</BODY>
</HTML>






Return to JavaScript index



Valid HTML 4.01!

© Jo Edkins 2005