Beginner's JavaScript

../Pictures/spectacles-xxx.jpg
This tutorial is for those of you who are thinking of trying out programming, and have little or no previous experience. I have chosen JavaScript since it is an easy language to understand, whilst being extremely powerful. Although you probably know of JavaScript because it is the de facto scripting language within HTML pages, I'm not going to use a browser. Instead I'll use an interpreter based on the SpiderMonkey scripting engine (the JavaScript implementation within Mozilla Firefox, among others), called JSDB. I'll use this interpreter to create the output to the 99 bottles of beer song.

Download the Interpreter

If you use Windows, the JSDB site has a simple one click download link available directly on the home page. The download page also provides versions of the interpreter for Linux, and Mac OS X.
All three downloads are provided as archived files. The contents should be extracted into a folder on your hard disk. For Windows, I used C:\Program Files\jsdb, on Linux or Mac OS X, you might want to use /usr/bin/jsdb.
Next, you'll want to test that the interpreter does it's job. Open a console window (in Windows click on Start, then Run..., then type cmd.exe and click on OK), then move to the installed directory (for Windows, within the console, type cd "C:\Program Files\jsdb" then press Enter), then type jsdb perfect.js and press Enter, and you should see something similar to this:
BeginnersJavaScriptImages/console-1.png
So far so good. Next you'll need a text editor to be able to modify the JavaScript source code files yourself. Windows has Notepad, Linux and Mac OS X have too many to list, so just choose the one you like best. Now open the JavaScript file we just ran (for Windows, within the console, type notepad perfect.js then press Enter), and you should see something like this:
BeginnersJavaScriptImages/editor-1.png
Better and better. Our next objective (drum roll please) will be to write a simple program which will write out the 99 bottles of beer song. The lyrics of the song can be found on the 99 bottles site. Yes, there is already a JavaScript version, but it won't help you cheat much, because it's designed for a web page, and not for our interpreter – nice try though.

A Little Background Material

That quick look at perfect.js in the text editor gave us some information about how a program is laid out in JavaScript. Basically it's a mix of special punctuation, reserved words, and textual characters. Interesting, but before we jump to the wrong conclusions, let's get things into perspective.
JavaScript was developed by Netscape for their browser. They produced a couple of manuals for the language, which are freely available, and can even be downloaded onto your computer. The first is “The Core JavaScript Guide”, which is exactly what we want, because it gives an overview of the language itself. The second is “The JavaScript Reference Guide”, which provides a list of objects and functions available. Both manuals are a little dry in style. An excellent book for beginners is “JavaScript: The Definitive Guide” by David Flanagan, which has an earlier edition available online from O'Reilly. Finally, for those in a hurry, then the article “A re-introduction to JavaScript” by Simon Willison, gives a whirlwind overview.

99 Bottles of Beer, First Cut

Wait a minute, you say, I don't know how to program. Fine, I prefer the hands on approach, so I'll guide you through our program, and introduce you to the concepts as we go. I think this is more satisfying.
First let's look at the song, and make some observations:
1.   99 bottles of beer on the wall, 99 bottles of beer.
 Take one down and pass it around, 98 bottles of beer on the wall.
...
97.  3 bottles of beer on the wall, 3 bottles of beer.
     Take one down and pass it around, 2 bottles of beer on the wall.

98.  2 bottles of beer on the wall, 2 bottles of beer.
     Take one down and pass it around, 1 bottle of beer on the wall.

99.  1 bottle of beer on the wall, 1 bottle of beer.
     Take one down and pass it around, no more bottles of beer on the wall.

100. No more bottles of beer on the wall, no more bottles of beer.
     Go to the store and buy some more, 99 bottles of beer on the wall.
I put in the ellipsis (...) because the other lines are so similar. Before you ask, no we are not going to just print all 100 couplets out verbatim, this is a programming exercise, so we want to use as little code as possible to do the job.
There is a lot of similarity, and some subtle differences. First, the similarities; couplets 1 to 97 are identical, except for the numbers. This is a good opportunity to use a variable. Next, the subtle differences; couplet 98 line two has 1 bottle, whereas all the previous couplets had n bottles. Couplet 99 has no more bottles. Finally, couplet 100 has No more bottles, and the second line starts quite differently.
If we take out the numbers greater than one and substitute them with a question mark (?), then we will have the following set of unique strings:
1.  ? bottles of beer on the wall, ? bottles of beer.
2.  1 bottle of beer on the wall, 1 bottle of beer.
3.  No more bottles of beer on the wall, no more bottles of beer.
4.  Take one down and pass it around, ? bottles of beer on the wall.
5.  Take one down and pass it around, 1 bottle of beer on the wall.
6.  Take one down and pass it around, no more bottles of beer on the wall.
7.  Go to the store and buy some more, ? bottles of beer on the wall.
Well, that certainly seems a little easier. So let's put this into our program. I hope you've still got the console window open, otherwise follow the steps I outlined above.
I don't want to mix our code with that of JSDB, so we'll create a file 99beers.js in a new folder tutorial. Within the console, type mkdir tutorial then press Enter, now create the file to edit (for Windows, within the console, type notepad tutorial\99beers.js then press Enter, then click on Yes to create the file.)
Type the following text into the editor, then save the file (for Windows, press Ctrl+s):
/*
 Prints the lyrics to "99 bottles of beer".
*/

// Unique lyric lines
var lines = [
  "? bottles of beer on the wall, ? bottles of beer.",
  "1 bottle of beer on the wall, 1 bottle of beer.",
  "No more bottles of beer on the wall, no more bottles of beer.",
  "Take one down and pass it around, ? bottles of beer on the wall.",
  "Take one down and pass it around, 1 bottle of beer on the wall.",
  "Take one down and pass it around, no more bottles of beer on the wall.",
  "Go to the store and buy some more, ? bottles of beer on the wall."
];

writeln(lines.join('\n');
Yes, alright, I'll allow you to cut and paste this time.
Good, now let's run our little program. Type jsdb tutorial/99beers.js then press Enter. As you can see, everything works just fine. Oops, actually, it doesn't:
BeginnersJavaScriptImages/console-2.png
Two firsts – your first JavaScript program, and your first interpreter error. This is a syntax error, not a bug. A syntax error means that the interpreter didn't understand what you wrote, a bug is a syntactically correct program which does something different from the programmer's intention.
The interpreter has given us some information about the error, it gives the line number, and it also shows the point in the line where the error occurred, and it gives a description of the error too. That helps a lot. Since there are two opening parentheses ((), there should also be two closing parentheses ()), so add a closing parenthesis just before the semicolon (;), and save the file. The corrected line should be:
writeln(lines.join('\n'));
Then run the program again:
BeginnersJavaScriptImages/console-3.png
Better. Now let's look at the code we've written so far. At the top of the page I have written a comment:
/*
 Prints the lyrics to "99 bottles of beer".
*/
This tells us what the program should do – though we're not quite there yet. Comments come in two flavours, multi-line as above, which begin with /* and end with */, and single line comments, which we'll see in a moment. Multi-line comments don't have to be on multiple lines. Comments are treated as whitespace by the interpreter, and can be placed anywhere that whitespace can appear.
Moving on, we have:
// Unique lyric lines
var lines = [
  "? bottles of beer on the wall, ? bottles of beer.",
  "1 bottle of beer on the wall, 1 bottle of beer.",
  "No more bottles of beer on the wall, no more bottles of beer.",
  "Take one down and pass it around, ? bottles of beer on the wall.",
  "Take one down and pass it around, 1 bottle of beer on the wall.",
  "Take one down and pass it around, no more bottles of beer on the wall.",
  "Go to the store and buy some more, ? bottles of beer on the wall."
];
This part contains a whole set of interesting concepts. First, there is the single line comment, which starts with // and ends with the end of the line. Then I have declared and defined a variable with the identifier lines. The var reserved word tells the interpreter that I'm declaring a variable. Since there is an equals sign (=) after the identifier it also knows that I'm specifying a definition.
This definition takes a bit of digesting, so let's do something a little simpler first:
var weight = 2.4;
This is a variable called weight which is defined as being the numeric literal2.4. This is called a statement, and the semi-colon (;) is used as a statement terminator. JavaScript has several data types, numeric literals, string literals, boolean literals (two actually, true and false), and objects. For example:
var speaker = "She said \"No really?\"";
This is a string literal. A string literal starts with and ends with either a quote ("), or an apostrophe ('), which are called string delimiters. If you need to use the delimiter character within the string literal, you can 'escape' it (make the interpreter ignore it) by preceding the character with the backslash character (\). The interpreter will not consider the character after a backslash to be the end of the string delimiter, and will silently remove the backslash from the string. Unfortunately, this means that the backslash character itself has to be escaped inside a string literal (just type it twice \\).
Of the many objects that JavaScript provides, two are particularly important, because of their frequency of use. The first is the dictionary, the second is the array. A dictionary is a collection of name-value pairs, and is also known by the names hash, hash table, or associative array. It is also the basic object in JavaScript, because objects have properties (data) and functions (methods), which have names and definitions (name-value pairs). An array is a sequence of data objects, which can be referenced by an index, similar to houses in a street, each with its own house number. Our definition of lines above, is an array of strings. The first string has the index value of 0, and the last string has the index value of 6. JavaScript arrays are zero based.
Dictionary and array objects can be created using the new keyword:
var dictionary = new Object();
var array = new Array();
but better still, you can use object literal syntax to do the same thing, but with fewer keystrokes:
var dictionary = { name : value, name : value };
var array = [ value, value, value ];
Which is exactly what I did above, including the string literals within the array itself. The last line of our fledgling program is as follows:
writeln(lines.join('\n'));
Yep, that's the one that gave the syntax error. This line has two objectives; first it satisfies us because it prints out our array, secondly it tests all the code that we have written so far.
Again it needs a little explaining. We are calling two different methods, writeln, which is actually a built-in function of the global object, provided by JSDB, and join, which is a method of the array object.
In JavaScript, methods can receive parameters, within the parentheses, and can return a value. The method writeln can accept a string as its parameter, which it then outputs to the console, and appends a newline. The join method of our lines array takes all the elements of the array and converts and appends them into a single string, using the string provided as a parameter (in this case '\n', the newline character) to delimit each element. It then returns the string to the caller. This could also have been done in two steps, but would have required an extra variable:
var result = lines.join('\n');
writeln(result);
If writeln returned a value, such as the number of characters output, this information will be lost, unless we store it in a variable. In this case, it doesn't matter, because we're not interested in any returned value, only in the action that writeln performs.
You can find more details about the objects defined by JSDB in the help file jsdb.html which you'll find in the installation folder you used for JSDB. For the built-in objects supplied by SpiderMonkey, the JavaScript interpreter, see “The JavaScript Reference Guide”, which, as I already mentioned, you can download to your hard disk.
We still need to write the actual code which will output the lyrics to the song. To do this, we will declare a function and then call this method. From our initial analysis, we have seen that couplets 1 to 97 can be performed in a loop, substituting the question mark with the current number of bottles. Couplets 98, 99, and 100 are special, and must be handled outside the loop.
Delete the last line of our current file, (the one with writeln(lines.join('\n')); on it) and then add:
// Print the lyrics to standard output
function printLyrics() {

  // Couplets 1 to 97: "99 bottles..." to "3 bottles..."
  for (var i = 99; i > 2; i--) {
    writeln(lines[0].replace(/\?/g, i.toString()));
    writeln(lines[3].replace(/\?/g, (i – 1).toString()));
    writeln();
  }

  // Couplet 98: "2 bottles..."
  writeln(lines[0].replace(/\?/g, "2"));
  writeln(lines[4]);
  writeln();

  // Couplet 99: "1 bottle..."
  writeln(lines[1]);
  writeln(lines[5]);
  writeln();

  // Couplet 100: "No bottles..."
  writeln(lines[2]);
  writeln(lines[6].replace(/\?/, "99"));
}

printLyrics();
I'll let you cut and paste again, but you're going to have to write something on your own sometime, so why not try now? To avoid indigestion, we'll look at this in small doses. First let's take a look at the function definition, and method call:
function printLyrics() {
  /* ... */
}

printLyrics();
I've substituted the body of the function definition with an ellipsis (...) to avoid clutter, we'll look at the function body in a moment. To tell the interpreter that we're defining a function we use the function reserved word, followed by the identifier (the function name). Then we specify the parameters that the function expects inside the parentheses. Since we aren't expecting any, this is empty – you still need to put in the parentheses though. If we did want parameters, we would have specified them by using identifiers, separated by commas, like this:
function functionName(name, name, name) { /* ... */ }
After the parameters, cosily wrapped in their parentheses, comes the function body, wrapped in curly braces, which comprises zero or more statements. The curly braces are block statement delimiters and are used anywhere you want to group a set of statements together. Since the closing curly brace is itself an end of statement delimiter, you don't need the semi-colon (;) after it.
Finally, we call the method to print out the song. Simply defining the function doesn't actually execute any code, you've got to actually call the method for that to happen. So why did I call it printLyrics, and not, say, print_lyrics, or PrintLyrics, or printlyrics? They'd all be accepted by the interpreter, but JavaScript naming conventions uselowerCamelCase, and so do I. JavaScript uses CamelCase for constructors, such as new LyricsPrinter(), but we'll look at constructor methods a little later.
Now let's take a look at the body of the function, starting with the loop:
  for (var i = 99; i > 2; i--) {
    writeln(lines[0].replace(/\?/g, i.toString()));
    writeln(lines[3].replace(/\?/g, (i – 1).toString()));
    writeln();
  }
This is quite similar to the function definition. We've got parentheses and curly brackets again. The loop I chose is probably the most popular type in JavaScript – the for loop. Inside the parentheses you put an initial expression, a condition expression, and an increment expression, separated by semi-colons (;). Our initial expression is:
var i = 99
That is, create a variable called i and set it to the numerical value 99. The condition expression is:
i > 2
This must evaluate to a boolean value, either true or false. Think of it as asking the question “is the expression true?”, or in this case “is i greater than 2?”. While the evaluated boolean value is true, the statements in the for loop will be executed. This could mean that the loop is never executed, if the first evaluation is false, which is sometimes intentional, or that the loop never terminates if the condition always evaluates to true, which is not usually intentional, and is known as an infinite loop.
The increment expression is very brief:
i--
This simply means decrement the variable i by one. It is shorthand for i = i – 1. The increment expression is executed after all the loop statements are executed.
Why did I name the variable i? Why do you see multiple loops with variables i, j and k in other people's source code? Again this is a naming convention, but less strict than variable or function names, so bottlesOfBeer would be perfectly acceptable, and probably more readable. This particular naming convention is historical, and comes from the Fortran programming language, where undeclared variables were typed according to there first letter, and i was the first letter for integers. Thought you'd like to know.
So what is happening inside the loop? Let's take a look at the first line, which will help us figure out the rest. I've 'exploded' the line into its separate components:
    writeln(                                     );
            lines[0]
                    .replace(                   )
                             /\?/g,
                                    i.toString()
We've already met writeln, so there's nothing new there. lines[0] means “get the element from array lines at index 0”, which retrieves the string "? bottles of beer on the wall, ? bottles of beer.". Since a string is an object in JavaScript, it has properties and methods, which can be accessed using the dot notation, so lines[0].replace( ... ) means call the replace method of the string object. The replace method of the string object is described in “The JavaScript Reference Guide”, and expects two parameters; a regular expression and a replacement string, and it returns the duely modified string.
Regular expressions are a powerful mechanism for string manipulation, made famous by the Perl programming language, and imported into almost every other programming language, including JavaScript. Essentially, it allows you to match and identify patterns of characters in a string. I've used a regular expression here in order to substitute every occurrence of the question mark character (?) in the string, with the current number of bottles of beer (the value of the variable i). You can create a regular expression object like this:
var re = new RegExp(“\?”, “g”);
But I prefer the shorthand syntax:
var re = /\?/g;
The pattern to match lies between the slash characters (/), in this case we are looking for a single question mark (?), but since that character has a special meaning in regular expression syntax, we have to escape it with the ubiquitous backslash character (\). The g signifies “global”, in other words it will find all occurrences of a question mark in the string.
The second parameter for the replace method is the string which will replace the question marks. Since i is a numeric object, we can use the toString() method which will convert the number to a string.
The next statement performs a similar operation on the second line of the couplet, using one less than the current number of bottles of beer (the variable i). I had to use brackets here to ensure that the value of i - 1 was converted. The last statement produces a blank line:
    writeln(lines[3].replace(/\?/g, (i – 1).toString()));
    writeln();
Good. The rest of the function body handles the special cases for couplets 98, 99 and 100. Since there is nothing new there, I won't bother to explain it all again.
So, we've completed our little program. Lets run it and see what happens. From the console, type jsdb tutorial/99beers.js then press Enter. The results should be something like this:
BeginnersJavaScriptImages/console-4.png
If something went wrong, and you get syntax errors, here is the complete source code of our program to date:
/*
 Prints the lyrics to "99 bottles of beer".
*/

// Unique lyric lines
var lines = [
  "? bottles of beer on the wall, ? bottles of beer.",
  "1 bottle of beer on the wall, 1 bottle of beer.",
  "No more bottles of beer on the wall, no more bottles of beer.",
  "Take one down and pass it around, ? bottles of beer on the wall.",
  "Take one down and pass it around, 1 bottle of beer on the wall.",
  "Take one down and pass it around, no more bottles of beer on the wall.",
  "Go to the store and buy some more, ? bottles of beer on the wall."
];

// Print the lyrics to standard output
function printLyrics() {

  // Couplets 1 to 97: "99 bottles..." to "3 bottles..."
  for (var i = 99; i > 2; i--) {
    writeln(lines[0].replace(/\?/g, i.toString()));
    writeln(lines[3].replace(/\?/g, (i – 1).toString()));
    writeln();
  }

  // Couplet 98: "2 bottles..."
  writeln(lines[0].replace(/\?/g, "2"));
  writeln(lines[4]);
  writeln();

  // Couplet 99: "1 bottle..."
  writeln(lines[1]);
  writeln(lines[5]);
  writeln();

  // Couplet 100: "No bottles..."
  writeln(lines[2]);
  writeln(lines[6].replace(/\?/, "99"));
}

printLyrics();
If you get fed up of trying to fix the syntax errors, then just cut and paste the code into your file. I understand, I'm human too.
Now you hand in your masterful work to the teacher, and wait for the accolades. The teacher, who may have been a Bastard Operator from Hell in a previous life, gives you 6 out of 10. Only just sufficient, if you go to an Italian school. “WTF?”, I hear you cry. Well let's see how we can improve things a bit.

99 Bottles of Beer, the Director's Cut

JavaScript is an object oriented programming language, though up to now we have used it as if it were a procedural language. In effect, any variables and functions which are not specifically applied to an object are applied to the global object. Our little program added two names to the global object; lines and printLyrics(). While we can argue our case for printLyrics(), we can't do the same for lines, no other function except printLyrics() needs it, so it it shouldn't be globally available.
Secondly, our printLyrics() function is a black hole - it gives nothing back. True, it correctly computes the lyrics, but it also sends them directly to standard output (the console). If anybody wanted to modify the computed lyrics they'd have to get the output from the console. Which means that Tom, Dick or Harry would probably have to rewrite printLyrics() if they wanted to format it as, say, an HTML page.
Finally, the file always prints out the lyrics, whether we want them or not. So it can't become part of a library for a bigger application. Alright, use your imagination here, I know that few people will be clamouring to use this stuff in an application, but try substituting getLastTransactions() from your bank account for printLyrics(), and I think you'll get the point. The function does too much on its own, and doesn't let anyone else do something with the results.
Right then, back to the keyboard. We'll make an object which we'll call NinetyNineBeers (you can't start an identifier with a number in JavaScript, because the interpreter will think that it is a numeric literal), and we'll give it title, author, and lyrics methods. We'll also hide the lines variable. The lyrics method will return an array of strings, and then we'll write the test method in another file, toConsole.js, so that 99beers.js can be included as a library. Ready?
/*
 Supplies the title, author and lyrics to "99 bottles of beer".
*/

function NinetyNineBeers() {

  // Returns the song title
  this.title = function () {
    return "99 Bottles of Beer";
  }

  // Returns the song author
  this.author = function () {
    return "Anon";
  }

  // Returns the song lyrics
  this.lyrics = function () {  

    // Unique lyric lines
    var lines = [
      "? bottles of beer on the wall, ? bottles of beer.",
      "1 bottle of beer on the wall, 1 bottle of beer.",
      "No more bottles of beer on the wall, no more bottles of beer.",
      "Take one down and pass it around, ? bottles of beer on the wall.",
      "Take one down and pass it around, 1 bottle of beer on the wall.",
      "Take one down and pass it around, no more bottles of beer on the wall.",
      "Go to the store and buy some more, ? bottles of beer on the wall."
    ];

    // The array to contain the lyrics
    var result = [];

    // The regular expression, to substitute '?'
    var re = /\?/g

    // Couplets 1 to 97: "99 bottles..." to "3 bottles..."
    for (var i = 99; i > 2; i--) {
      result.push(lines[0].replace(re, i.toString()));
      result.push(lines[3].replace(re, (i – 1).toString()));
      result.push("");
    }

    // Couplet 98: "2 bottles..."
    result.push(lines[0].replace(re, "2"));
    result.push(lines[4]);
    result.push("");

    // Couplet 99: "1 bottle..."
    result.push(lines[1]);
    result.push(lines[5]);
    result.push("");

    // Couplet 100: "No bottles..."
    result.push(lines[2]);
    result.push(lines[6].replace(re, "99"));
    return result;
  }
}
Don't panic, this modification took just five minutes to make, and most of our original code is still there, trust me.
First let's analyse the constructor function:
/*
 Supplies the title, author and lyrics to "99 bottles of beer".
*/

function NinetyNineBeers() {
  /* ... */
}
Alright, I admit that I also changed the comment to reflect what the new code does. The constructor function is just like previous functions, except that, when used with the new reserved word, it will create a new object, with all the stuff we define in the constructor function shoved kicking and screaming into the object. I kept to the CamelCase naming convention to show that it is a constructor function. To create the object you'd write something like this:
var song = new NinetyNineBeers();
Now we get to the interesting stuff, where you get to see just a little of the power and flexibility of JavaScript. Conceptually, when you use the new reserved word, JavaScript creates an object which it then 'gives' to the constructor method.
But the constructor method has no parameters, you quickly point out. Glad you're on the ball, well, it actually places the object in a virtual variable called this(this is also a reserved word, so you can't use it for your own variables.) Now we can reference this inside our constructor and add properties (variables) and methods (functions) to it. When our constructor function terminates, the new object will contain these properties and methods. Let's see that in action with the title function:
  this.title = function () {
    return "99 Bottles of Beer";
  }
Here we have a function definition as a function expression, which is slightly different from our previous function definition syntax. The first line reads “for the given object (this), create a property called title, which is a function with no parameters, and contains the following statements ...”. If you go back to our created variable, song, we can now call that method by writing:
var title = song.title();
The other important point is that our new function gives back a value – the song title. To do that we use the return reserved word. The expression after return will be returned to the caller.
The author() function is very similar, so I'll skip that one. Now let's look at the changes we made to our old printLyrics() method:
  this.lyrics = function () { 

    // Unique lyric lines
    var lines = [
      "? bottles of beer on the wall, ? bottles of beer.",
      "1 bottle of beer on the wall, 1 bottle of beer.",
      "No more bottles of beer on the wall, no more bottles of beer.",
      "Take one down and pass it around, ? bottles of beer on the wall.",
      "Take one down and pass it around, 1 bottle of beer on the wall.",
      "Take one down and pass it around, no more bottles of beer on the wall.",
      "Go to the store and buy some more, ? bottles of beer on the wall."
    ];

    // The array to contain the lyrics
    var result = [];

    // The regular expression, to substitute '?'
    var re = /\?/g

    // Couplets 1 to 97: "99 bottles..." to "3 bottles..."
    for (var i = 99; i > 2; i--) {
      result.push(lines[0].replace(re, i.toString()));
      result.push(lines[3].replace(re, (i – 1).toString()));
      result.push("");
    }

    // Couplet 98: "2 bottles..."
    result.push(lines[0].replace(re, "2"));
    result.push(lines[4]);
    result.push("");

    // Couplet 99: "1 bottle..."
    result.push(lines[1]);
    result.push(lines[5]);
    result.push("");

    // Couplet 100: "No bottles..."
    result.push(lines[2]);
    result.push(lines[6].replace(re, "99"));
    return result;
  }
Since it's not printing anything anymore, I changed the name. I also moved the lines variable inside the function definition. That means that it will only exist within the scope of the function (when the function is executed.) There is no way it can be seen from outside the function.
Next I created an array, called result, to contain the lines of text (strings) of the lyrics. I substituted all the old writeln calls with result.push calls. There is no add method for arrays, but the push method adds an element to the end of the array (it is used together with the pop method to create a stack.)
I also added a variable re, which contains the regular expression to substitute all occurrences of the question mark (?) with the current number of bottles of beer ( the variable i). Looking at the old version, I realised that I was creating the same regular expression twice in a loop that cycles 97 times – which isn't terribly clever, or efficient.
Finally I added the return result statement so that the caller receives the created array.
Like I said, most of the original code is still there, but we've gained plenty of flexibility, and our object is now pure JavaScript (no references to the JSDB supplied objects), so we could use it in an HTML page if we wanted.
Now we need to write our test method in toConsole.js. Create this file in the tutorial folder, just as you did for the 99beers.js file. Then add the following code:
/*
 Prints the 99 beers lyrics to the console.
*/

var song = new NinetyNineBeers();
writeln(song.lyrics().join('\n'));
This code has mostly been covered above, so I'll not bother you by explaining it. Now the moment of truth, lets run the program. From the console, type jsdb -load tutorial/99beers.js tutorial/toConsole.js then press Enter. If everything goes well you should get exactly the same results as before:
BeginnersJavaScriptImages/console-4.png
At some later time, along comes Tom, Dick or Harry, and writes a little JavaScript file called toHtml.js, which outputs the song in HTML format:
/*
 Prints the 99 beers lyrics to HTML.
*/

var puts = function (str) { document.write(str); }
var song = new NinetyNineBeers();

puts("<h4 class='Heading_20_4' style='margin: 0 1cm 0 1cm'>");
puts(song.title());
puts("</h4>");

puts("<div class='Text_20_body' style='margin: 0 1cm 0.5cm 0; text-align: right'>");
puts(song.author());
puts("</div>");

puts("<div class='Text_20_body' style='font-size: 10pt; margin: 0 1cm 0 1cm'>");
puts(song.lyrics().join("<br />"));
puts("<br /></div>");
You can see the results for yourself on the 99 Bottles of Beer page. So our JavaScript program did end up in a web page after all.

The Source Code

For the extremely lazy, all three files can be downloaded from here:
You'll probably have to right click to download them, because otherwise the browser may try to execute the code.

Conclusions

I hope that you found this tutorial useful. It is difficult to judge whether there is too much or too little material for a complete beginner. Hopefully, as I use this tutorial on neophile and neophyte programmers, I'll get enough feedback to smooth off some of the sharp edges. Which, I suppose, is a nice way of apologising for the current state of the contents.

Why JavaScript?

Why did I choose JavaScript for a beginner's tutorial? I said before that it is a powerful and flexible programming language, which is true. Just as importantly, it is currently being rediscovered as more than just a toy language inside the web browser, thanks to the popularity of Ajax, Asynchronous JavaScript and XML.
But this is just the tip of the iceberg. JavaScript can be used as a more terse data interchange format than XML, using JSON. It is used extensively within Mozilla Firefox to power the user interface, via XUL, and to createFirefox add-ons. This can even be extended to create your own applications, based on the Mozilla Firefox source code, using XULRunner. Even Google have chosen JavaScript as the main programming language for their offline web application framework, Google Gears.
As a professional programmer, I am more than convinced that knowing how to program not just well, but excellently, in JavaScript is already a key component of anyone's CV, and will become even more important in the future.

Further Reading

Take a look at most of Douglas Crockford's articles on JavaScript, which he has conventiently grouped together on this page. He has also created the JSLint program. This program checks the construction of Javascript programs, and offers suggestions to improve the code, and reduce potential errors.
One of the better sources of clean JavaScript (there are, unfortunately, plenty of sources that do not fall into this category) is Peter Paul Koch's QuirksMode web site.
Another well written JavaScript library, used by the Ruby On Rails framework is Prototype. Another source of JavaScript source code is script.aculo.us, which uses the Prototype library.
I have also written a more complex tutorial on my company site.