JavaScript programming

(Under development)

This lecture presents a brief example-based summary of client-side programming in JavaScript.


There seem to be more bad books on JavaScript than on any other language.

These may be the best two:

Here are two others that are not so bad:

Why client-side programming?

Which client-side scripting language?

JavaScript summary

Niederst Robbins describes HTML as implementing the structural component of a Web page, CSS as implementing the presentation component, and JavaScript as implementing the behavioural component.

A JavaScript program

JavaScript is very similar to PHP (but not to Java!). Like PHP, it is a dynamically typed language. Differences are that variables do not start with a dollar character (yay!), constants are defined differently (const a = 1;), local variables must be declared (var a = 1;), different open/close script tags are used, strings are concatenated with a plus character (as in Java and Python), the object model is quite different, it (JavaScript) uses event-oriented programming (in Web applications), and it can be used as a functional programming language. See the following examples for more differences.

More JavaScript features

Basic types. Booleans (false, true), numbers (123, 456.7e2), strings ("Hello, world\n"). That's all. Note that values false, 0, '', null, undefined and NaN are all interpreted as false in boolean expressions.

Operators. Similar to those in Java and PHP. Use === and !=== for testing equality.

Array types. Literal arrays, e.g., var mixed = [0, false, "a"]. (See below for more details.)

Object types (cf. PHP associative arrays, Java maps). Literal objects, e.g., var pm = {first: "Julia", last: "Gillard"}. Here, first and last are called properties. Properties may be accessed as pm[first] or pm.first. Properties may be updated by pm.first = "Tony"; pm[last] = "Abbott". New properties may be added similarly. So far, similar to PHP associative arrays. However, functions may be associated with objects. (Described later.) To iterate over the properties of an object:

for (name in pm) { ... ... }

Objects may inherit properties from a prototype (or parent) object. To avoid seeing inherited properties, it is possible to write:

for (name in object) {
    if (object.hasOwnProperty(name)) { ... ... }

Strictly speaking, arrays are a particular kind of object. The indexes of the array are its properties as an object. The length of an array is one more than its greatest index. Elements may be deleted from an array (delete a[3]) without changing its length. Hence, to iterate over the elements of a dynamic array:

for (index in array) {
    if (array[index] !== 'undefined') { ... array[index] ... }

This processes the array elements in arbitrary order. You could also use an indexed for-statement, but you may still need to check that array elements are not undefined.

(Indexed) arrays and objects may be arbitrarily nested. This property forms the basis of JSON, described later.

Function definitions. These are superficially similar to function definitions in PHP and Java:

function name (parameters) { body }
But...functions may be stored in data structures, e.g., as properties of objects, and name may be omitted to define an anonymous function. It is good practice to declare all local variables of each function at the start of its body.

JavaScript events

In Web applications, JavaScript actions are normally invoked when one of the following events occur:

Simple JavasSript programs and techniques

Note the simple use of the DOM API in these examples for selecting and changing parts of the browser window. For example, document.forms returns a list of forms of the current document, document.forms[0] returns the first form of the document, and document.forms[0].exButton returns the element of the form with name exButton.

Important methods for selecting elements of a window (or document) are getElementById (which returns the unique elment with a given id), getElementsByName, getElementsByTagName and getElementsByClassName (all of which returns the list of elements with the given name / tag name / class name (resp.)).

Having used the DOM API to select an particular element in a document, you can change the content of that element by assigning to its innerHTML attribute:

element = getELementById('foo');
element.innerHTML = "<span class='bar'>some new text</span>";

Note also the use of .value to get the value of a form element, particularly a form element of type input.

Note that syntax errors are not reported by the JavaScript interpreter; it simply generates incorrect behaviour. This can make debugging difficult; be careful.

Many browsers provide features or add-ons to support JavaScript development, an example is Firebug in Firefox.

More example programs

This simple noughts and crosses program was provided by Chris Gray. It uses the DOM to update elements of a simple HTML table.

This more complex loan calculator program comes from JavaScript: The Definitive Guide, Sixth Edition by D. Flanagan (O'Reilly, 2011). It illustrates the use of the HTML5 <canvas> element as a drawing surface.

Exercise. Rewrite the noughts and crosses program using the HTML5 <canvas> element. This will require detecting events (mouse clicks) and the location of events on the canvas.

Search for "HTML5 examples" for more examples of sites built using HTML5 and JavaScript. One such example site is HTML5 Demos and Examples.

Other JavaScript programs

See pp.310-337 of Web Database Applications, Second Edition by Williams and Lane.

See pp.465-512 of Web Design in a Nutshshell, Third Edition by Niederst Robbins.

Many useful JavaScript scripts for a variety of purposes are easily found on the Web, e.g., at W3Schools' JavaScript Tutorial.

HTML Document Object Model for JavaScript

This summary is taken from JavaScript for the World Wide Web by Negrino and Smith. It is used for navigating around an HTML document.

A window has a document, a frames[] (a list of frames), a location, a locationbar, a menubar, a name, a parent, a screen, a self, a status, a toolbar, a top, and other elements.

A document has an anchor, an anchors[] (a list of anchors), a cookie, a form, a forms[], an image, an images[], a link, a links[], a location, a referrer, a title, and other elements. (In Netscape, a document also has a layer and a layers[].)

A form has an action, an elements[], and a method. An element may be a button, a checkbox, a hidden, a password, a radio, a radios[], a reset, a select, a submit, a text, or a textarea. Each element has a (containing) form, a name, a type, and a value.

Recall that important methods for selecting elements of a document are getElementById, getElementsByName, getElementsByTagName and getElementsByClassName.

See this chapter from (an old edition of) the definitive JavaScript text for a detailed description of the HTML Document Object Model.

See the W3C Recommendation for full details


The combination of HTML (content), CSS (presentation), DOM and JavaScript (behaviour) is sometimes called DHTML (Dynamic HTML).

Separating content from behaviour

Just as we separate content from presentation by using external style sheets to avoid cluttering the HTML content with presentation information, so we should also separate content from (JavaScript) behaviour to avoid cluttering the HTML content with behavioural information. We can use external JavaScript definition files as a partial solution, but this does not go far enough. The HTML content will probably still be cluttered with "javascript: code" links, with JavaScript "onClick" events, and so on.

See Behavioural Separation and Unobtrusive JavaScript for advice and examples of how to design and implement this separation properly, making essential use of the DOM.

The basic idea of unobtrusive JavaScript is to run a JavaScript function when a document (without JavaScript code) is first loaded to insert multiple onevent="JavaScript action" attributes to selected elements throughout the document.

But details of this technique is more advanced than required for this course.


JavaScript used to be incompletely and inconsistently implemented by different browser developers. It was poorly documented, and there are many examples of bad programming style in books and online tutorials.

However...JavaScript is actually quite a good programming language (if you avoid its many bad parts), since the ECMAScript 5 standard was published (2009) all major browser developers have committed to implementing the standard faithfully, and the texts and documentation is definitely improving.

Moreover...The development of HTML5 with its standard JavaScript API, and the opportunity for scripting multimedia, interaction, HTTP requests and more is making JavaScript more important than ever. The ability to script HTTP requests (i.e., make HTTP requests under program control) in particular, using a combination of JavaScript, DOM and XML (or JSON), called Ajax, is becoming increasingly important as a way to develop applications with rich user interfaces. See below.