Real programming with JavaScript


For quite some time I have not had a high opinion of JavaScript. This is probably because in the late 90s I spent far too much time trying to get so-called Dynamic HTML to work reliably on the version 4 flavours of Netscape and Internet Explorer. And also because JavaScript is far too often used in stupid and annoying ways on the Web, to name a few: pop-up windows, window resizing, dialog boxes, cursor trails, and JavaScript-only links and forms.

However I have recently discovered that, as with many other programming languages, the power of JavaScript can be harnessed for good as well as evil. JavaScript is a surprisingly powerful programming language and is well worth a detailed look.

What is JavaScript?

It’s a tired old refrain, but it bears repeating: JavaScript is NOT Java. It seems the complication was deliberate but sadly misguided.

  • Java is a full-featured compiled programming language developed by Sun Microsystems. Java originally found popularity by providing extra functionality to web browsers in the form of “applets” - mini applications that could be run inside web pages. These days, Java typically finds more use in stand-alone applications.

  • JavaScript, originally known as LiveScript, was developed by Netscape to allow greater interaction between the Netscape browser and Java applets. It seems some brightspark in the marketing pushed the name change to JavaScript and a lifetime of confusion was born. It was not long before JavaScript was being co-opted for use in the sort of abuses mentioned above.

JavaScript is an object-oriented programming language commonly used to add scripting features to web browsers. Actually, that’s slightly inaccurate - true JavaScript is found in Netscape and related browsers (the Mozilla family), in Internet Explorer the equivalent is JScript, and most modern graphical web browsers have scripting capabilities based on the standard ECMAScript.

Since 1997 the European Computer Manufacturers Association (ECMA) has maintained the ECMAScript specification for a standard web client scripting language. By adhering to this specification as a minimum, the makers of web browsers have been able to provide much improved cross-browser functionality in scripting, although JavaScript and JScript both add proprietary extensions to the basic standard.

But enough of this - the easiest way to find out what JavaScript is really like is to have a bash at it.

The easiest programming environment

If you’ve got a recent web browser and a text editor, then you’re ready to write JavaScript. It couldn’t be easier.

Listing 1

<title>JavaScript Example 01</title>
<script language="JavaScript">
// JavaScript can appear in the head section
<script language="JavaScript">
// JavaScript can appear in the body section

In a web browser, a JavaScript must be read from inside a web page. See listing 1 for an example. This is a complete web page with two complete JavaScripts inside. Both the web page and the JavaScripts produce no notable output, but it shows the rules that apply: JavaScripts can appear in the section or the <body> section of a web page and JavaScripts are contained inside tags. A common idiom is to enclose JavaScript code inside HTML comment tags:

 (JavaScript code goes here)

This is for historical reasons - when JavaScript first appeared many browsers did not recognise the <script> tag, and as a result all of the program code would be printed to the browser window (not a desirable outcome!) The vast number of browsers used these days recognise the <script> tag so the problem has largely disappeared, but the programming practice remains.

The examples in this article show only the JavaScript code but full working examples are also linked. Example scripts in this article have been inserted into the <body> part of a web page.

To run the examples, simply load the example file into your web browser - there is no need to load it from a web server, you may open it directly from your own hard disk. If you want to re-run a program, simply click the reload button on the toolbar of your browser.

Input - Output

Readers of my recent article on “Eight things programming languages do” will recall that input and output provide ways for programs to communicate with the outside world. Let’s look at some of the options available for input and output in JavaScript.

The simplest is window.alert(), which puts up a dialog box with a message and an “OK” button. The next is window.confirm(), which produces a dialog box with a message, an “OK” button and a “Cancel” button. (For my money, these buttons would have been better labeled as “Yes” and “No” - and on some Macintosh browsers that’s how they appear - but to the best of my knowledge you can’t alter the button labels.) The window.confirm() dialog box produces (or “returns”) a value that can be stored in a variable: if the user clicks the “OK” button the value is TRUE or FALSE if the user clicks “Cancel”. The third method is window.prompt(), also a dialog box with a message, a text input field, an “OK” button, and a “Cancel” button. If the user clicks “OK”, whatever they typed into the input field is the value returned.

Listing 2

var visitorName = window.prompt( "What is your name?", "" );
var proceed = window.confirm( 
   "Are you ready to go further with JavaScript " 
    + visitorName + "?");
if ( proceed == true )
    window.alert ("That's great " + visitorName);

(Live example currently deactivated)

Listing 2 illustrates the use of three input/output methods in JavaScript. Firstly, the variable visitorName stores whatever the user typed in response to the question “What is your name?” in the window.prompt() dialog box.

window.prompt() in the Safari browser (Mac)

Figure 1

The next question appears in a window.confirm() dialog box (figure 2) and the value TRUE (for “OK”) or FALSE (for “Cancel”) is stored in the variable proceed.

window.confirm() in the Safari browser (Mac)

Figure 2

If the user agrees that they are ready to proceed, they are then given a short message of encouragement in a window.alert() dialog box.

window.alert() in the Safari browser (Mac)

Figure 3


In “Eight things programming languages do” I said that a function is a batch of programming instructions that can be used repeatedly. Let’s refine that definition a bit more. In JavaScript (as in most other languages) a function may:

  • receive zero, one or more arguments, and

  • produce (or “return”) exactly one value

The normal purpose of a function is to perform some actions on the argument(s) to produce some result that becomes the returned value.

We have already seen some examples of JavaScript functions. The function window.confirm() takes as an argument a string that is printed in the dialog box as a message. The value returned by window.confirm() is either TRUE or FALSE, depending on what button the user clicks.

The function window.prompt() takes two arguments: firstly, a message string like the one used in window.confirm(), and secondly a default value that is inserted into the text input field in the dialog box. In listing 2, the second argument is “” - an empty string but you can experiment by changing this to whatever you like.

The window.alert() function is a rare exception. Although it takes one argument, a message string just like window.confirm(), window.alert() does not return a value.

Gotcha - addition or concatenation?

In listing 2, you might have noticed that several values were joined by a plus sign (+) to produce a single argument. For example, the expression “Are you ready to go further with JavaScript ” + visitorName + “?” produces a question directed personally to the user. If the user entered their name as “Sam”, the single value passed to window.confirm() would be “Are you ready to go further with JavaScript Sam?”. This is the process of “string concatenation”.

One of the limitations of JavaScript is that the plus sign (+) is reused (or “overloaded”) as the operator for mathematical addition and as the operator for concatenation. Look at listing 3:

Listing 3

var firstNum = window.prompt("Input a number", 0);
var secondNum = window.prompt("Input another number", 0);
var total = firstNum + secondNum;

(Live example currently deactivated)

In this script the variable firstNum holds a number received by the first input box, and secondNum holds the number entered in the second input box. Then these two numbers are added together and held in variable total, which is output to the screen in an alert box. If we input the number 11 into the first input box (firstNum) and 22 into the second (secondNum), the value output in the alert box (total) will be 33, right? Wrong!

Oops - that’s not addition!

Figure 4

Instead of adding 11 and 22, they have been joined together as if they were two strings of characters “11″ and “22″. And as far as JavaScript is concerned, that is what they are. The window.prompt() function allows you to type anything at the keyboard - not just numbers - so it must return a string.

Some languages (such as C and Java) are “strongly typed”, that is when a variable is declared the programmer must also indicate what type of data it will contain (e.g. string, integer, Boolean) and the variable can only hold values of that type. Like other so-called scripting languages (such as Python and Perl) JavaScript is “loosely typed”. In this case variables are not restricted by data type - in fact at different times in a program one variable may hold different types of data.

Which brings us back to our problem - our two variables hold the values “11″ and “22″ which we want to add as if they were numbers. The plus sign (+) only works as mathematical addition if the values on both sides are numbers, otherwise it works as concatenation (joining two strings). Clearly we need a way to convert the values to numbers - fortunately JavaScript provides it in the Number() function, as shown in listing 4:

Listing 4

var firstNum = window.prompt("Input a number", 0);
var secondNum = window.prompt("Input another number", 0);
var total = Number( firstNum ) + Number( secondNum );

(Live example currently deactivated)

The Number() function takes a string value as an argument and tries to return it as a number, which gives the desired result.

JavaScript CAN do mathematics.

Figure 5

But Number() can’t perform miracles - it can’t even turn the string “eleven” into the number 11. The string passed into Number() must contain a recognisable number (positive or negative, integer or decimal fraction), otherwise it will return the special value NaN (short for Not a Number). You can put this to the test with the code in listing 4.

DIY functions

JavaScript allows us to declare our own functions, so let’s make a prompt dialog box that will only return numbers (listing 5).

Listing 5

function numberPrompt( msg, dflt )
var errMsg = "Your answer must be a number - ";
    var result = Number( window.prompt( msg, dflt ) );
while ( isNaN( result ) )
        result = Number( window.prompt( errMsg + msg, dflt ) );
    return result;

var firstNum = numberPrompt("Input a number", 0);
var secondNum = numberPrompt("Input another number", 0);
var total = firstNum + secondNum;

(Live example currently deactivated)

To dissect the function: var errMsg = “Your answer must be a number - “; * The variable errMsg holds a simple error message that will be included in the dialog box if the user inputs a non-numeric value.

var result = Number( window.prompt( msg, dflt ) );

* The arguments to numberPrompt() are passed onto an ordinary window.prompt() dialog box. The return value from window.prompt() is converted to a number and stored in the result variable.

while ( isNaN( result ) )
    result = Number( window.prompt( errMsg + msg, dflt ) );

* The while instruction is a repetition instruction - it will repeat the instructions in the body of the loop inside the curly brackets {} for as long as the condition in brackets () is true. The condition - isNaN( result ) - literally means “is result not a number?”. If the answer to this question is TRUE, then the body of the loop is evaluated and then the condition is checked again. In this case the program will repeatedly prompt for input until the user enters a number.

Hopefully it is clear that if the user enters a number in the first place, the answer to the condition isNaN( result ) will be FALSE and the program will never enter the body of the while loop.

return result;

* At the end, tell the function what value to return.

The new numberPrompt() function allows us to rewrite listing 4. We can now be sure that total will always be a number because numberPrompt() will only return numeric values to firstNum and secondNum.


This introduction barely scratches the surface of what JavaScript has to offer but I hope you are keen to explore and experiment further.

The input/output methods shown here are rudimentary and I would not normally (if ever) recommend them for use on real live web pages. However, they do provide some ‘quick-and-dirty’ ways to get information into and out of programs while learning about JavaScript. In a later article we will look at some more sophisticated input/output methods.

tech.thingoid Gosbell First published: PC Update June 2004

One Response to “Real programming with JavaScript”

  1. Boomerang Says:

    Good on you tech.thingoid and thanks look forward to reading and experimenting with Javascript