JavaScript Introduction

JavaScript is an interpreted language initially implemented in the Netscape world wide web browser. JavaScript is not Java plus or minus. It is a new language that has a superficial resemblance to Java, partly because of a common application area (HTML / web) and common ancestry (C with object oriented features).

JavaScript programs are run on the client computer usually by a web browser which must have JavaScript enabled (for Netscape check `Options' then `Network Preferences' then `Languages'.)

In contrast, server-side cgi-bin programs involve the transmission of information from the client back to the server which computes the result and returns it to the client.

Simple Example

JavaScript is executed by the web browser. The most basic action of a JavaScript program is to write into the HTML document. This kind of use of JavaScript resembles programming with macro-processors which are common in assembly languages. Below are some temperature conversion data which could have been written into the HTML file on the server computer but are instead calculated on the client computer by a JavaScript program:-

The Effect:

The Source Code:
< S CRIPT LANGUAGE="JavaScript">
< ! --
document.write('Centigrade to Farenheit<BR>');
for(i = 1;  i <= 10;  i++)
 { c = i*10;
   f = c*9/5+32;
   document.write(c + '°C = ' + f + '°F');
// -- >

Note, spaces have had to be inserted into the SCRIPT and comment tags of the source code above to prevent at least one browser from interpreting it as active JavaScript! A real SCRIPT tag consists of the less-than symbol, <, immediately followed by the word SCRIPT, no spaces etc..

JavaScript code is enclosed in SCRIPT tags. The use of a comment to further enclose the code will cause a browser without JavaScript to ignore it. (In addition, some JavaScript code can be placed in the HEAD of an HTML page.) Double slash, //, introduces a JavaScript comment running to the end of line. <!-- This is an HTML comment. -->

Try turning JavaScript off and on in your browser (see Options button, Network Preferences then Languages) and reloading this page.

Random Images etc.

The accompanying image is aligned left, centre or right depending on a JavaScript program that uses the seconds of the time of day as a random number to control the layout. Try Reload.

Similar programs can be used to display one of a number of alternative images, links, sections of text or advert's "at random".

The HTML source of this page is [here].

Copyright © L.Allison Department of Computer Science, Monash University, Australia 3168 / 1997