Loops and Some Things More
<font color="#ff0000" size=4>WebTV JS "Bug" - Reload Page (cmd-r)</font>


For all the "bells-and-whistles" that accompany JS it is easy to lose sight of the programming base that must be used to bring life to a page. One of the powerful tools in this base are the conditionals already described, "if" and "if...else". The other, and probably the work-horse of JS, are the loops. These make possible repeat operations, and at the heart of them is a conditional which continues the loop until the conditional specification is met. This section looks into some of the various types of loops there are in JS.

"onClick" Loop In other programming languages each line is numbered and, if it is desired to return to that line, all that is necessary is to put in a "GoTo" statement referencing that line. This creates a program loop: a start and then a return to the beginning of that line. In JS, there is no exact counterpart. Rather, functions are made to take its place. A function, once defined, is stored until called upon again, thus creating the loop. Functions have been introduced earlier, but now it is necessary to look at them in a little more detail. In this, the most general situation, a function is given a name by which it can be called and whatever it is supposed to do is enclosed within braces.

function namefunc(){JS Statements;}


The parentheses after the name of the function designate that input is to be passed through there and output returned from there as well.

The only means available in J(HTML)S to enter input is by use of a form text-input statement and it is also the only means to gain a differing output during program execution. For this, whatever is entered in the input-text window must be named, and this is the name given as an attribute in the text-input tag. The output is displayed by a text-input window as well, and it may be beneficial in this instance to associate with this a readonly="readonly" attribute, which makes the window read-only.

<form name="vardisplay">
<input type="text" name="varinput">
<input type="text" name="varoutput"
            onClick="namefunc()" readonly="readonly">
</form>


Now, it is necessary to ask, "How is the input variable transferred to the function?" It is being input in a window appearing on this document from the form named vardisplay containing the element named varinput and is given by value. In JS this is written:

usevar=window.document.vardisplay.varinput.value


It is this that the function needs as a variable and to which it is set equal. When this variable is used and a result obtained, the result can be written to the output window named in the form.

window.document.vardisplay.varoutput.value=result


Knowing now how to put variables into and get an answer from a function, an onClick loop can be illustrated. In this, example, envision a choice of pets from a pet store. All pets available are on a list, and for every customer that asks the list must be gone through again to see if that pet is available. Only a dog, a cat, and a mouse are available in this inventory for simplicity, and for each an "if" is made use of to determine whether this was the pet desired. The loop is made from the onClick. A click transfers the request to the function to determine if the pet is there. The function, as usual must be stored at some point prior to its use as is illustrated:

<script>function choix(){var skp="*";
var pets=window.document.opt.want.value;
pets=pets.toLowerCase();
   if(pets == "dog")
    {window.document.opt.stock.value=message1;skp="got"};
   if(pets == "cat")
     {window.document.opt.stock.value=message2;skp="got"};
   if(pets == "mouse")
     {window.document.opt.stock.value=message3;skp="got"};
   if(skp == "*")
     {window.document.opt.stock.value="Sorry. Ask again."};}
</script>

<form name="opt">
Kind of Pet <input type="text" name="want">
<input type="button" value="Let's See" onClick="choix()">

<input type="text" name="stock"readonly="readonly">
</form>


A variable skp has been introduced so that if the original definition for it, skp="*", is not changed it will be known that the asked for pet is not on the list. Take care to note how the braces are nested. Here is how it works in practice. Make up an example and try it as well.

Kind of Pet 






"while" Loop Well, that is a loop. The only problem is a button has to be clicked each time in order to continue the loop. It would be more desirable if there was a way to continue the loop without this. The while loop provides one way. The construct for it is entirely within a JS block as follows:

<script>
var testword="aword";
while (testword != response)
{ Do what is programmed here }
</script>


This is just a fancy kind of "if" statement. It says, "While the response is not the same as the testword, do whatever is in the braces. In the event there is a match, i.e., testword=response, skip it all". For the example below, make up a test word, and see what happens. A button has to be clicked only for the purpose of entering the test word.




When using a while loop caution must be exercised. The loop will continue as long as the condition tests true. Certain applications will never test false unless an appropriate indicator is included. For example, there is no way to stop operation of the loop on the left, below, since the condition can never be realized, but by putting in a counter the loop will stop after the third "alert":

Infinite LoopEnding Loop
while(true){
alert("Want to stop?")}
var i=0;
while(i <= 3){
i=i+1;
alert("This will Stop.")}


Increments & Sequences What is that funny-looking addition there? The one that stopped the looping in the previous example. It has to be remembered that what is to the right of an equals sign has whatever operations are specified done. The quantity on the left just stores the result. So, in the example,i was initialized to 0. This value for i was added to 1, making i=1. On the next pass i is 1 and when added to 1 resets the value of i to 2. This can be continued as long as desired, for the example three times. Concatination of a string variable can be sequenced in the same way, the initalization being a string variable the value for which is a space. It is a good exercise to concatinate the string variable "x" as many times as may be desired and to print the result of each loop.

Incrementing is done so frequently, that JS has three ways of designating it, each of which is given below:

i=i+1
i += 1
i++


Any one of these can be used, the choice being a matter of convenience or custom. The last incrementing shorthand is unique. Starting at a higher value the increments can be decreased by one by using ++i instead of i++, which increases each increment by 1.

"for" Loop The for loop is by far the most useful and most frequently encountered loop. It has the form:

for(initial value;    test;    increment)
{ do these statements }


In this, an index is initialized, an if statement tests if a predetermined limit has been reached, and if not a new increment is set. Before making use of the new increment all statements which are in between the braces are executed.

Using a for loop considerably streamlines the code and the operation of it for the pet shop example given at the beginning of this section. A modification is made for this example by storing all available pets, the total for which is npet, in an array. Omitting inputs and outputs for this the basic code is as follows:

pets=pets.toLowerCase();
for(i=0; i < npet; i++)
{ if(pets == stock[i] )
{window.document.choice.see.value="Message";}}


The pet requested, pets, is compared using an if statement against each pet in the array. The index for the array is taken from the for statement. When a match is found a message is displayed. All items in the list are gone through in seeking a match. Though it may not visually appear to be so, the following makes use of the routine just described (check source).

Kind of Pet 






Since every item in a list is gone through in seeking a match, this type of data search is termed sequential access. When the number for an item in the data is known, the item can be obtained immediately, without going through all items. This is known as random access.

JS Test-Bed 1 - - JS Test-Bed 2



<< PreviousNext >>