GEOG5870/1M: Web-based GIS A course on web-based mapping

Program statements

The previous page introduced various language elements and described the way in which code should be written. It mostly focussed on expressions – small fragments of code (such as 'x < y', or 'a == 1') that can be evaluated to produce a result; the result typically being 'true' or 'false'. Some of the examples showed expressions in the context of a larger program, but in general we have not considered how we actually make the program do something. In order to get the program to carry out some action, we need to use statements, and this page introduces some basic statements. All programs consist of a series of statements that are carried out in order.

Simple and compound statements

We have already seen some statements in the examples shown so far. Our first code showed a very simple program that consisted of one line of JavaScript, embedded within an HTML page; that JavaScript program consisted of the single statement 'alert()', with a text string containing a message included as a parameter to the statement. In this case, 'alert()' is a function call: we are causing the program to carry out a (pre-defined) function. Other single-line statements include variable declaration statements using 'var' as we saw on the previous page.

On other occasions we need to carry more complicated actions that can be expressed in a single statement, and for these we need to use compound statements. Compound statements are treated within the wider structure of the program as a single statement, but they consist internally of a number of sub-statements. The sub-statements are grouped together within curly brackets '{}'. We've already seen this in some of the examples shown so far, but it is illustrated below. The code shows the generic structure of an 'if' statement. If a certain condition is met (the supplied expression is evaluated and the result is 'true') then the associated statement is carried out; if the result of the expression is 'false', then the statement is ignored, and we continue on to the next statement in the program.

a) Generic structure:
if (expression)
  statement

b) An example using a simple statement:
if (x > 0)
  alert("x is positive");

c) An example using a compound statement:
if (x > 0) {
   alert("x is positive");
   positive_values++; // update a counter
}

The "b" code above shows an example using a single statement. Note that, as described on the previous page, the layout is flexible. Here, the sub-statement which depends on the if statement is shown indented on the next line, but it could be continued on the same line if preferred. The sub-statement ends in a semi-colon, as all statements usually should. In this example, if the condition is met, then the alert() function is called. But what happens if we want a series of actions to occur? How can we distinguish between a series of actions to be carried out if the if statement is true, and the next statements that will be used if the if statement is not true? The answer, is that we use a compound statement. The code "c" shows a compound statement with two sub-statements. These are grouped together using '{}', and this block is treated as a single statement in the overall structure. The example in "c" thus still fits the generic template of "a". The compound statement consists of two sub-statements, and both of these are terminated with a semi-colon as usual. If the if statement is false, then the entire compound statement is ignored.

The example above illustrated a single case of a uncomplicated compound statement. In practice compound statements may consist of many sub-statements. It is also important to note that compound statements can be nested: one of the sub-statements in a compound statement may itself be a compound statement, and so on...

Control statements

The first set of statements we shall consider are control statements. Control statements regulate the flow and branching of the program, and thus allow complex behaviours to be programmed. We have already met the most fundamental of control statements – the 'if' statement.

if, else, else if

The code above illustrated the basic form of the if statement. This can be expanded using the optional else clause, as shown in below. Using the basic form shown above, an expression is evaluated and then a statement is carried out if the expression is true. If it is not true, we move on to the next statement. We also move on to that next statement after carrying out our sub-statement if the expression was found to be true: thus, the next statement will always be used. But, what happens if we want to specify one behaviour if the expression is true, and an alternative behaviour if the expression is not true? For that, we can use the if .. else form of the statement. Code "a", below, shows the generic form of the if statement using the else clause, and "b" shows a simple example. In this example, we display one message if x is greater than 0, and another message if not. But wait a moment, you say, that second statement isn't quite right! What if x is zero? A common use of the else clause is to follow it with another if statement. An example is shown in Figure "c". Note that 'else if' isn't a special form of the if statement in it's own right, we are simply following a standard 'else' clause with a new 'if' statement.

a) Generic structure:
if (expression)
   statement
else
   statement

b) An example using simple statements:
if (x > 0)
   alert("x is positive");
else
   alert("x is negative");

c) Using an if ... else if pattern
if (x > 0)
   alert("x is positive");
else if (x < 0)
   alert("x is negative");
else
   alert("x is zero");

The final part of the example in code "c" uses an 'else' clause followed by a statement other than 'if'. It is always good practice to finish an if...else sequence in this way: the final option will always by used if no other conditions have been met.

switch

The if...else form of the if statement allows you to build up programs which can branch in multiple ways depending on the results of various expressions. In the example above, we used a sequence of tests against the variable 'x', and it is easy to imagine situations in which many more than two options (plus a catch-all) might be considered. Whilst 'if...else' can be used for these situations, this involves continually considering conditions, which isn't very efficient. JavaScript offers a more efficient structure for testing multiple values of a single variable: the switch statement. The switch statement is divided up into a set of alternative actions, using the case keyword. This is illustrated below:

switch(x) {

   case 0:
      // Do something if x=0
      ...statements...
      break;

   case 1:
      // Do something if x=1
      ...statements...
      break;

   case 2:
      // Do something if x=2
      ...statements...
      break;

   default:
      // Do something if the previous cases were not matched
      ...statements...
      break;

}

Note that all of the case options are followed be a series of statements which are terminated with the break keyword, which causes program execution to move beyond the outer switch statement. A switch statement should include a series of case options, plus a final catch-all state, identified using the special keyword 'default'. The whole body of the switch statement is written as a compound statement, and thus placed within '{}'.

while and for loops

The control statements if and switch allow alternative branches of a program to be executed in different circumstances. An alternative set of control statements allow various parts of the code to be repeated a number of times. These are known as loops, and they make writing programs far easier and more efficient. The first of these statements is while statement, which is illustrated below. Code "a" shows the generic form of the statement, whilst "b" shows an example:

a) Generic structure:
while (expression)
   statement

b) A worked example
var x = 1;
while (x < 10) {
   document.write(x);
   x++;
}

The generic form is straightforward: whilst the given expression is true, then repeatedly carry out the statement.

Code "b" shows how we might use this. First all we set up a counter variable x, and then start a while loop. We will carry out the statement forever whilst x is less than ten. in this example, we are using a compound statement with two sub-statements. In the first of these sub-statements, we use the function document.write() to write the current value of x on screen (in this case, without any spacing or line breaks, so it would look like this: 12345... etc). The function document.write() uses the write() method of the pre-defined document object. Back to our example: our next sub-statement is 'x++;'. As described on the previous page, '++' is a special operator that increments a variable by one. It is referred to as a unary operator, because it only requires one argument (variable). This causes our counter variable to advance, and without it we would be stuck inside the loop forever, as x would always be less than ten. Loops which run forever are known as infinite loops, and are a common form of bug.

The example shown in Figure "b" contains three important operations on the counter or loop variable: it is initialised (var x=1), it is tested (x<10) and it is incremented (x++). All of these stages are vital to the loop running as expected. JavaScript offers an alternative structure for loops that places these three operations in the same place, with the intended result that it is harder to make a mistake and forget one of the operations. The alternative structure is a for loop, and it is illustrated below, using the same sequence of instructions as above.

a) Generic structure
for (initialisation; test; increment)
   statement

b) A worked example
for (x = 1; x < 10; x++) {
   document.write(x);
}

Summary

This page has introduced the idea of statements – parts of the program that do something. We have concentrated on control structures, which affect the branching and looping of a program, and used only a couple of simple 'actions' to actually generate some form of output. In the next pages, we shall explore more fully how JavaScript is embedded in a web page, andshow some example of simple programs that actually do something worth doing.


[ Next: Adding JavaScript to a web page]
[Course Index]