JavaScript 3: Program Structures

The if Statement

This takes the form:

if (condition statement) {
   zero or more statements;
}

The condition statement computes a Boolean value, true or false, using the comparison operators, ==, !=, >, <, >= and <=. If the condition evaluates to TRUE the statements in braces are executed, otherwise they are skipped.

The extended form of the if statement takes the form:

if (condition statement) {
   zero or more statements;
   } else {
   zero or more statements
}

The layout of the words and symbols is not important so long as the syntax is correct - you could write if(condition statement){zero or more statements;}else{zero or more statements} but this is harder to read. Note the way the symbols are aligned in vertical columns - this can prove useful in debugging when you may have one '}' too few or too many and the alignment helps to find the missing or extra symbol. The statements in {} form a block of statements and JavaScript is similar to many algorithmic languages like C and Pascal in being block-structured.

The condition statement may include more than one Boolean expression linked by AND, OR or XOR operators. The if statement is the chief means in a JavaScript program to control execution of lines of code. Note that each statement inside the statement block is ended by a ';'.

For example:

if ((x < 50) && (-50 < x)) {                     //write comments like this
    y = (x * x * x);                             //compute the cube of x
    astr = "The cube of " + x + " is " + y;      //form an output string
    } else {                                     //for values of x outside -25 to +25
    y=null;                                      //give y a value of null
    astr=x + "is too big to compute the cube";   //form an alternative output string
    document.FindCube.cubeout.value=astr;
    }
}

This uses two conditions to check that the input value (x) is within the required range (-50 to +50). Values larger than 50 might exceed the limits of the JavaScript interpreter to store and represent the result. The second line uses the * operator to compute the cube of x. The third line uses the '+' operator to concatenate the elements of a string. Text like 'The cube of' is placed in quotation marks while variables such as x are written without quotation marks. Note the use of spaces inside text to format the output correctly.

Here is the code in action:


Enter a number in the range -50 to +50 in the first box. The program will return the cube of this number.



Note the form of the onClick statement:

onClick="cube_of_x(document.FindCube.getx.value)"

The item in brackets is a parameter which passes the value of the the user's input to the function cube_of_x. This allows us to use x in the function as a synonym or alias for the much longer form which is used only once. This keeps the code more compact and easier to read. The parameter drills down to the value provided by the user in the input box by following the object hierarchy of the browser:

document.form_name.element_name.value

You will learn more about writing functions and the object hierarchy later, for now we are still learning the basics of JavaScript code.

This is the FORM from which the code is called:

<HR><FORM NAME="FindCube">
Enter a number in the range -50 to +50 in the first box. The program will return the cube of this number.<P>
<INPUT TYPE="text" NAME="getx" SIZE=10>
<INPUT TYPE="button" VALUE="Click to submit" onClick="cube_of_x(document.FindCube.getx.value)">
<INPUT TYPE="reset" NAME="rest"><BR>
<INPUT TYPE="text" NAME="cubeout" SIZE=30 VALUE="">
</FORM><HR>

Note here the way the function is called using the onClick event to trap the user's action of clicking on the button. When the onClick event is fired the function is called and the action is carried out. There are a number of events in a window which are available to the Javascript programmer, we will meet these later.

Here is another example:


Enter your favourite soccer team in the first box. A message will then appear:


The function which processes the user input is as follows:

<SCRIPT LANGUAGE="JavaScript">
function footballteam() {
  if (document.TextTest.sin.value=="Liverpool") 
    {document.TextTest.sout.value="You'll never walk alone!";}
  else 
    {document.TextTest.sout.value="You should only follow the best!";}
}
</SCRIPT>
The form is defined like this:
<FORM NAME="TextTest">
Enter your favourite soccer team in the first box:<P>
<INPUT TYPE="text" NAME="sin" SIZE=20>
<INPUT TYPE="button" VALUE="Click to submit" onClick="footballteam()">
<INPUT TYPE="reset" NAME="rest">
<INPUT TYPE="text" NAME="sout" SIZE=60 VALUE="">
</FORM>

The user's input is taken into the text area called 'sin' and picked up by a function called 'footballteam' when the button is clicked. The program does nothing more than output a message according to the team entered by the user. As an exercise you should add a few more teams - Port Vale, Doncaster, Stenhousemuir, etc. The input is case-sensitive so if the user fails to use capitals and lower case in the same way as the test values the team will not be found.

This is a simple if..then statement with no additional complexity. There are two text fields on the form along with reset and submit buttons. The second text field is used for output - this is how data is output to a page in response to user input. Either text field could be used for input or output, it just happens that we have chosen to use the first for input and the second for output. Typing text into the second field will have no effect because there is no code to process it.

Switch

In the case of the football teams there are clearly many possible user inputs (Gillingham, Stenhousemuir, etc) and the switch structure may do a better job.

switch (choice) {
case 0: astr='Youll never walk alone';  //can't punctuate 'youll' or the string is ended
break;       //exit if the test is met
case 1: astr='Remember 89';
break; 
default: astr='Forest we love you...';
break;
}

This might be called from a line such as:

<INPUT NAME="CALLIT" TYPE="BUTTON" VALUE="Click for Message" OnClick="Football_Team(document.footform.select_team.SelectedIndex)">

This passes the index from a select list to a function which processes it according to the position of the football team name in a select list (see Section 15 for more on select lists).

(Only works in IE.)

Enter your favourite soccer team in the first box. A message will then appear:

The while Statement

This takes the form:

while (condition statement) {
   zero or more statements;
   }

The while statement performs the statements in the statement block as long as the condition holds True. This is known as a 'loop' in programming. When the condition turns False the statements are no longer executed and the program moves to the next line of code after the closing '}'. Note that this form of a while statement may not execute the code in the statement block at all because the first test of the condition may return False.

In these variants of the while loop the condition is at the end so the statements will be executed at least once.

For example:

var i=1;
var oddsum=0;
var astr=null;
while (i<=100) {
       oddsum += i;
       i +=2;
}



A while statement can be exited before its condition returns False by using the break statement, for example the following line could have been inserted in the code above to close the loop at numbers greater than 49:

if (i>49) {break;} The continue statement is used in the opposite way to force execution back to the top of a while loop, for example:

while (i++ < 50) { x++; if ((x%2)=0) continue; sum +=x; }

This identifies numbers which divide by 2 with zero remainder and removes them from the calculation by forcing a return to the start of the loop before executing the final statement which calcualtes the running total.

The for Statement

The for statement provides a loop with a precise number of cycles such as 10 or 500. It is commonly used in mathematical calculations and also in processing arrays and other structured objects. It takes the form:

for (initialisation; condition; update) {
     for_block
    }

The initialisation section sets a variable which acts as a counter of the loops completed. The condition section contains is a Boolean expression of the same form found in if and while statements. The update section changes the value of the variable set up in the initialisation section. For example:

for (var i=1; i<=10; ++i) {
    document.form_name.element.value=i;
    for (j=1;j<=10000; ++j){}
    }
}

This simple code outputs the value of i which increases from 1 to 10. The first loop includes a second one nested inside it which simply counts to 100 before continuing; more accurate delays can be created with the date object, more of which later.




Here is the form from which the code is called:

<FORM NAME="ForDemo">
<INPUT TYPE="button" VALUE="Click me to see some numbers" onClick="number_list()">
<INPUT TYPE="reset" NAME="rest"><BR>
<INPUT TYPE="text" NAME="numbersout" SIZE=30 VALUE="">
</FORM>

Functions

The code we have seen so far is mainly found inside functions. A function is a block of code which has a name and which can be called from different parts of a HTML document and also from within other functions. JavaScript code does not have to be inside a function but that is probably its most common location. Functions are defined by:

Here is the function for the cube problem considered above:

function cube_of_x(x) {
if ((x<=50) && (-50<=x)) {
    y = (x * x * x);
    astr = "The cube of " + x + " is " + y;
    } else {
    y=null;
    astr=x + " is too big to compute the cube";
    }
    document.FindCube.cubeout.value=astr;
}

This function has one argument which picks up the value entered by the user from the form input box (document.FindCube.getx.value). This allows 'x' to be used inside the function instead of the much longer 'document.FindCube.getx.value' and is also good programming practice. 

The argument x only exists while the function is in use and cannot be accessed from outside of it. This is called the scope of a variable, the areas of the program from which it can be accessed. When a function is called, space is made for variables which are declared inside the header (the arguments) and in the body of the function. These variables are only accessible from within the function and are destroyed when the function finishes. Thus it is possible to have three functions with a variable called x (or any other common name) and they are quite separate. It is possible to include variables inside a function which are defined outside it, typically 'global' variables declared outside of any function. A variable inside a function may have the same name as one outside the function, the former taking precedence over the latter. It is not possible to change the value of a local variable from outside the function to which it belongs. It is possible to change a global variable from inside a function but this may lead to confusing code and should be avoided where possible. 

Simple (scalar) variables are passed to functions by value, as in function (x), where x is an integer or a simple string. In this case the function makes a copy of the variable for use during execution and it is destroyed afterwards. Some variables, on the other hand, are passed to functions by reference rather than by value, that is the address of the variable is passed so the variable remains global and the function can change its contents. This is the case with objects and arrays (which are objects in Javascript) where the function does not make a copy of the variable but accesses the original item through its address in memory. Considering the size to which objects and arrays may grow this makes good sense because it avoids the need to copy large amounts of data.

It is generally good programming practice to use local variables within functions, to return the result of a function to the place from which it is called, and to leave variables outside a function unaffected by its operation.

The cube function could also be written as:

function cube_of_x(x) {				//x is created by the function as a local variable
if ((x<=50) && (-50<=x)) {			//the scope of x is limited to the function only
    y = (x * x * x);				//as is the scope of y and astr
    astr = "The cube of " + x + " is " + y;
    } else {
    y=null;
    astr=x + " is too big to compute the cube";
    }
    document.FindCube.cubeout.value=astr;
    return;
}

or:

function cube_of_x(x) {
if ((x<=50) && (-50<=x)) {
    y = (x * x * x);
    astr = "The cube of " + x + " is " + y;
    } else {
    y=null;
    astr=x + " is too big to compute the cube";
    }
    document.FindCube.cubeout.value=astr;
    return astr;
}

Here we see the use of the keyword return with either a null value or a return parameter. The return parameter sends the value back from the function to the point in the program from which it was called. The return parameter makes a value computed inside the function available outside the scope of the function. The line document.FindCube.cubeout.value=astr; addresses the document object outside the scope of the function and does the job but in a way which would upset a programming purist. The return astr line would pass the value of astr out of the function so that the main program could assign it to the document object.

Here is the code for the while example shown above:

function oddnumbers (){
var i=1;
var oddsum=0;
var astr=null;
while (i<=100) {
       oddsum += i;
       i +=2;
      }
document.WhileDemo.oddsout.value=oddsum;
return oddsum;    //returns value of oddsum to calling point
}

Here is the code for the for loop example:

function number_list() {
for (var i=1; i<=10; ++i) {
    document.ForDemo.numbersout.value=i;
    for (j=1;j<=10000; ++j){}
    }
return;
}

This function has an empty parameter list as there is no user input to collect.

A function may return a value to the point from which it is called, for example to a form or to another function.

Return to JavaScript Menu