Writing Simple JavaScript Programs

This section is intended to get you started writing elementary programs in JavaScript. We will not attempt to explain all the peculiarities of the programming language. We will try and explain the logic behind those parts of the language which are easily explained, and treat as arbitrary rules to be learned by rote those which are either actually arbitrary, or too time consuming to attempt to explain.

Examples will be given on the assumption that a Mozilla Browser is being used on a Windows system. If you are using Linux you are probably aleady `computer literate' enough to work out the differences. If you're using a Mac, I'm afraid I can't help, but most things should be similar.

The aim is to get you writing simple programs quickly, not to teach you all about writing complex programs. If you want to find out more about the language and `real' programming, we will provide hypertext links and a bibliography which you can follow up.

A First Program

Here is the simplest `useful' program:
<script>
document.write('Hello world!')
</script>
Click here to run this program. It will pop up in a new window.

On the browser window you can use the pulldown `View' and `Page source' to confirm that that the program is indeed exactly as above.

You can use `Save as' on the browser to save your own copy of the program in a subdirectory of your JavaScript work directory. Double click on this and you will see that it runs in exactly the same way.

Program structure

The program proper is just the middle line:
document.write('Hello world!')
What this does is to write into a web document the text:
`Hello world!'
The browser displays this web document. This instruction is sometimes called a `function call'. It causes something to be done; what is does is predefined by the words `document.write'.

What is written is determined by the programmer-supplied text included between the two quote symbols. (NB these are both the same single closing quote on the keyboard.) Any text (except for another single quote!) which appears there will be displayed. A piece of text in quotes is refered to as a `text string' or `character string' or sometimes just a `string'.

We will explain the purpose of the other two lines shortly.

Things to Try with the Simple Program

Save the program from the link above aand then open it in Notepad.

Change the message

Change the text in the quotes to something else. `Save' the file from Notepad. Open it in Mozilla which will execute the new version of the program.

Add another message

You can include as many `document.write' instructions of the form shown as you like, provided that each is either on a separate line, or separated from the previous instruction by the semicolon `;' symbol. Try adding another message this way.

Printing on a new line

You may have noticed that the two messages above appeared on the same line. To print on a different line use:
document.writeln('Some message')
This prints the message followed by a new line. Try it. Did it do what you expected?

JavaScript and HTML Web Documents - a short digression

No, I didn't lie to you. document.writeln does put things on a new line. The reason you didn't see it on a new line is because it was part of a web document.

Go back to the web document you created earlier to see how how this could be done, open it with Notepad and type in some text which includes blank lines. Now open it in a browser. See what has happened?!

Now insert the text:

<pre>
At the top of the document, and open it again.

Explanation: The HTML language in which Web documents are written ignores all multiple spaces, new and blank lines, unless told not to do so. One way to make it recognise these in the `preformat' instruction <pre>.

Because of the close relationship between JavaScript and Web documents, both HTML and JavaScript instructions have to appear in most JavaScript programs. However, HTML is easy to recognise beacuase all instructions are written between the symbols `<' and `>'.

The two other lines in our original program, <script> and </script> are HTML instuctions, the first to tell the browser that a JavaScript program follows, and the second to say that it is finished. Most HTML instructions come in pairs, one to indicate where something starts, and another where it finishes. The second instruction like </script> is usually read as `not script'.

Really printing on a new line

document.write('..') adds the text within the quotes to a `virtual' web document created by the browser. To make the blank lines in this visible it needs to start with the HTML instruction <pre>.

It should be fairly obvious how we can do this. this program does it. Use View Page Source to check how it was done.

Add a message to the reader of the program

It cannot be stressed too strongly that a good program is easy to follow and makes sense to the reader! You can add `comments' which do not cause the program to take any additional action, but which help the reader to follow what is going on. Any line or part of a line beginning with `//' is treated in this way.

Arithmetic in Programs

As well as printing messages, computer can of course do arithmetic. Here is a simple program to do a calculation:
<script>
// program to do a calculation
document.writeln('<pre>')
document.writeln('This program calculates 23.6*(1-4.2)/(3.0+2.1)')
document.writeln(23.6*(1-4.2)/(3.0+2.1))
</script>
You can run and copy it from here.

Important Point! Notice the difference between how 23.6*(1-4.2)/(3.0+2.1) is treated:

In the first case it is just a string of text and is, in the context of a `print' instruction, simply displayed exactly as it appears.

In the second it is treated as an expression and is evaluated using the computer's rules for arithmetic. These are mor-or-less the same as the conventional rules but include the following:

A fairly self explanatory range of higher functions is available, e.g. sin, cos, tan, log, exp, sqrt .. Their arguments must be written in `()'s and `log' means natural logarithm, `sqrt' is square root.

These may appear in expressions but their names must generally be preceded by Math. to indicate that this is a mathematical function. Thus:

document.write(2*Math.sin(3.142))
Note that upper and lower case letters are different in JavaScript so the name must appear exactly as shown. the `.' is part of the name. It is not permissable to put spaces in names. All of the following are thus wrong:
Document.write
document.wRite
math.sin
Mathsin
Another possible pitfall lurks for the unwary:

Exercises

The log function gives the natural log or ln. Write a program which calculates and prints a log to the base 10, using the relationship: ln x = ln (10) log10 (x)

(Calculate say, log10(3) which is a bit less than 0.5)

Variables

This is a key section which you must understand before proceeding further! Seek help if you are not entirely clear about it after trying the examples.

Consider the following program which you should copy from here:

<script>
// program to do a calculation
var x                        // This defines a variable called x
x = 23.6*(1-4.2)/(3.0+2.1)   // This gives it a value
document.write('x is ')
document.write(x)          // This displays the value
</script>
The overall effect of this is essentially the same as the previous program, except that it involves a new kind of entity, vital to effective programming, called a variable. It is so called because the value which it takes can be changed by equating it to different expressions on the right hand side of an instruction which always takes the form:
variable_name = expression
The form of this assignment instruction is identical to that of evaluating a formula. It is convenient to think of a variable in this context as being the same as a variable in a set of equations, although it is in fact a more general and flexible concept than that. At the very least, the use of variables facilitates the writing and developing of programs, and makes them easier to understand.

Consider the use of a program to evaluate expressions involving variables, whose values depend on other variables, i.e. a set of equations. This involves a slightly modified version of the previous program:

<script>
// program to solve two equations 
var x, y                    // This defines variables called x and y
y = Math.sqrt(23.6)              // calculate y
x = 23.6*Math.log(1.0+y)/(3.0+y) // calculate x which involves y
document.write('<pre>')
document.writeln('x is ', x)
document.write('y is ', y)      // This displays the values
</script>
You can run and copy this program here.

The instruction:

var x, y 
is called a declaration of the variables x and y. It consists of the word var followed by a list of the names to be given to the variables. These can be any combination of letters or numbers, but must start with a letter. The names may not include spaces, but the underscore character `_' may be used and is very useful in improving readability. Upper and lower case letters are different.

You should try to choose variable names which help the readers understanding of the program. In general you should not use meaningless name like `x' and `y', unless these have been used in the sepcification of the problem. Where standard symbols exist, e.g. `P' for pressure or `T' for temperature, use these with variants, e.g. T1, T2 or use descriptive names, e.g. T_reactor, Column_Pressure. Names can be up to 256 characters long, but typing very long names becomes tedious (and they can be mis-spelled).

Getting Programs Right

All the programs you have been shown so far are `correct', i.e. they should run without any error messages and produce the required results. The first programs you write from scratch will almost certainly not be correct!

Take time and care to write your programs. It is actually easier to get a program correct first time than to find an error once you nave written it!

Write your program down on paper, then type it in to the computer. This (a) forces you to think what you are doing and (b) gives you two chances to spot any mistakes.

There are two kinds of error which can occur.

The second kind are the hardest to track down.

To check program operation, before you load the .html fiule with the program in it go on the browser menu bar to:
`Tools ... Web Development ... JavaScript Console'

Click `Clear' to remove messages already in the window. Then load the program.

Error messages refer to line numbers in the program file. If you have this open in Notepad at the same time you can use its `Edit..Goto.. line number' feature to go to the line that appears to be incorrect. However, it is often the case that the instruction(s) that the debugger thinks are incorrect appear so as a consequence of another error which it may or may not have detected.

To give you practice in `debugging' programs, here is one which contains two errors.

And here is another which runs, but incorrectly.

Copy these, try them and correct them.

Concluding this Introduction ...

Go on to look at further programming ideas.