Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Teach Yourself Web Publishing with HTML 3.2 in 14 Days

Chapter 24 -- Working with JavaScript

Day 12

Chapter 24

Working with JavaScript


CONTENTS


Now that you have some understanding of what JavaScript is all about, it's time to take a look at some practical applications of the possibilities JavaScript offers.

In this chapter you'll learn how to complete the following tasks:

Note
The examples in this chapter, as with all the examples in this book, are available on the CD-ROM and at the Web site at http://www.lne.com/Web/Examples/Professional/.

Creating a Random Link Generator

A random link generator is basically a link that takes you to different locations every time you click it. In the past, the only way to implement such a link was through the use of a CGI script, but with JavaScript, all the previous server-side processing can now be performed by the Web browser itself.

In the following sections, you'll learn how to create three different random link generators. The first uses an inline <SCRIPT> tag and a single function, the second uses event handlers, and the third examines the use of arrays within a script.

Note
An inline <SCRIPT> tag is one that is embedded in the <BODY> section of an HTML document rather than in the <HEAD> section, as is the more common practice.

Exercise 24.1: The inline random link generator.

Because the JavaScript code for this generator will be incorporated in a standard HTML document, let's open the text editor or HTML editor you normally use for designing Web pages, and create a new file called random.html.

In this new file, create a basic document framework like the following one. You should recognize all the elements of this document from previous chapters, including the <A>...</A> tag combinations on the third-from-last line. If you were to run this document as it is, you would see a result like the one shown in Figure 24.1.

<HTML>
<HEAD>
<TITLE>Random Link Generator</TITLE>
</HEAD>
<BODY>
<H1>My random link generator</H1>
<P>Visit a <A HREF="dummy.html"> randomly selected </A>
site from my list of favorites.</P>
</BODY>
</HTML>

Figure 24.1: The Random Link page.

Now it's time to add some JavaScript code to turn the link into a random link generator. First, add a <SCRIPT> tag to the <HEAD> section immediately after the <TITLE> tag block:

<TITLE>Random Link Generator</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- the contents of the script need to be hidden from other browsers
  the JavaScript code goes here.
// End of script -->
</SCRIPT>
</HEAD>

The next step involves adding the code that generates the random links, based on a list of your favorite sites. Inside the <SCRIPT> tag-and comment tag-you'll create two functions: one called picklink()and one called random(). Let's start with picklink(). To create functions, you'll first define the framework like this:

function picklink() {
  your JavaScript code goes here.
}

Here's the code that actually makes the picklink() function work, here with a list of four sites to choose from:

function picklink() {

var linknumber = 4 ;
var linktext = "nolink.html" ;

var randomnumber = random() ;
var linkselect = Math.round( (linknumber-1) * randomnumber) + 1 ;

if ( linkselect == 1 )
   { linktext="http://www.netscape.com/" }
if ( linkselect == 2 )
   { linktext=" http://www.lne.com/Web/"  }
if ( linkselect == 3 )
   { linktext="http://java.sun.com/" }
if ( linkselect == 4 )
   { linktext="http://www.realaudio.com/" }

document.write('<A HREF="' + linktext + '">randomly selected</A>') ;
}

To help you understand what this code is doing, we'll examine it section by section. The first two lines following the function definition declare some work variables for the function: linknumber tells the function how many links it has to choose from when selecting a random link, and linktext is a work variable used to hold the value of the URL for the selected random link.

The next line-var randomnumber = random() ;-declares a variable called randomnumber and assigns a randomly selected value between 0 and 1 to it by calling the random() function (you'll define random() after we're finished with picklink()). The next line takes the randomnumber variable and uses it to create a second number called linkselect, which will contain an integer between 1 and the value set in linknumber.

The set of if statements that follows then checks the randomly selected value assigned to linkselect and, when a match is found, assigns a URL to the variable linktext. You can change these to be your favorite URLs or add any number of URLs you like here, but remember that if you add new URLs, you need to alter the value of linknumber so that it reflects how many links you've defined.

After you have a URL assigned to linktext, the next step is to create the physical link by using a document.write() method. You do this by writing this line:

document.write('<A HREF="' + linktext + '">randomly selected</A>') ;

The value inside the parentheses takes advantage of JavaScript's capability to add strings
of text together. In this case, '<A HREF="', the value of linktext, and the value of
'">randomly selected</A>' are added together to create a properly formed link tag.

With picklink() done, the other function we need to define is random(), which picks a randomly generated number between 0 and 1. This version uses the Date object to come up with a random number. The Date object is a way of getting the current system date and time in JavaScript:

function random() {
    var curdate = new Date();
    var work = curdate.getTime() + curdate.getDate();
    return ((work * 29 + 1) % 1-24 ) / 1024;
}
Note
JavaScript defines a better random number generator as the built-in Math.random() function. However, as of Netscape 2.0 and the pre-release 3.0, the Math.random() function is available only in the UNIX implementation of Netscape. This may have changed in the 3.0 version by the time you read this, in which case you can substitute the Math.random() function in place of the call to random() in picklink() and delete this function definition.

Now that you have both picklink() and random() defined in the <SCRIPT> part of the HTML code, all that remains to be done is to replace the original <A HREF= tag from the basic framework with the new link created by picklink(). You can do so in various ways, but the simplest method is by embedding a call to picklink() inside the body of your document, as shown here:

<P>Visit a <SCRIPT LANGUAGE="JavaScript">picklink()</SCRIPT>
site from my list of favorites.</P>
Note
Some JavaScript purists may argue that you should include <SCRIPT> blocks only in the <HEAD> section of an HTML document, and for the most part they are correct. But to demonstrate how inline script calls work and for the purposes of this exercise, the rules sometimes need to be broken. In the following exercise, however, you'll learn about a mechanism that allows a random link generator to be created without the use of inline <SCRIPT> tags.

The Completed Document
Here's the final random number HTML page, with all the JavaScript intact. You can also find this example on the CD-ROM:
<HTML>
<HEAD>
<TITLE>Random Link Generator</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- the contents of the script need to be hidden from other browsers
function picklink() {
// Remember to alter linknumber so it reflects the number of links you define
var linknumber = 4 ;
var linktext = "nolink.html" ;
var randomnumber = random() ;
var linkselect = Math.round( (linknumber-1) * randomnumber) + 1 ;
// Add as many links as you want here
if ( linkselect == 1 )
   { linktext="http://www.netscape.com/" }
if ( linkselect == 2 )
   { linktext="http://www.webcom.com/taketwo/" }
if ( linkselect == 3 )
   { linktext="http://java.sun.com/" }
if ( linkselect == 4 )
   { linktext="http://www.realaudio.com/" }
document.write('<A HREF="' + linktext + '">randomly selected </A>') ;
}
function random() {
    var curdate = new Date();
    var work = curdate.getTime() + curdate.getDate();
    return ((work * 29 + 1) % 1-24 ) / 1024;
}
// End of script -->
</SCRIPT>
</HEAD>
<BODY>
<H1>My random link generator</H1>
<P>Visit a <SCRIPT LANGUAGE="JavaScript">picklink()</SCRIPT>
site from my list of favorites.</P>
</BODY>
</HTML>

Exercise 24.2: A random link generator using an event handler.

Besides being bad style-wise, using inline <SCRIPT> tags can cause unpredictable problems when images are displayed on a page. To avoid such difficulties, the safest way to work with scripts is to use them only in the <HEAD> block, when at all practical.

This situation poses a problem for your random link generator, however, which needs to alter the value of a link each time it is used. If you can't include <SCRIPT> tags in the <BODY> of a document, how can the link be randomly selected?

Whenever you click a link, a button, or any form element, Netscape generates an event signal that can be trapped by one of the event handlers mentioned in Chapter 23, "Creating JavaScript Scripts." By taking advantage of this fact and the fact that each link in a document is actually stored as an object that can be referenced by JavaScript, you'll find it surprisingly easy to alter your existing script to avoid the need for an inline <SCRIPT> tag.

First, look at the changes that need to be made in the body of the document to accommodate the use of an event handler. In this exercise, the inline <SCRIPT> tag is replaced by a normal <A> tag as shown here:

<P>Visit a <A HREF="dummy.html">randomly selected</A>
site from my list of favorites.</P>

Next, associate an onClick event handler with the link by including the handler as an attri-bute of the <A> tag. When onClick is used as an attribute, the value assigned to it must represent a valid JavaScript instruction or function call. For this exercise, you want to call the picklink() function created previously and make the URL it selects overwrite the default URL defined in the <A> tag as HREF="dummy.html".

This job is easy to do because each link is actually stored as an object of type link, and the link type contains the same properties as the location object mentioned in Chapter 23. As a result, all you need to do is assign a new value to the HREF property of the link in the onClick event handler, as shown here:

<P>Visit a <A HREF="dummy.html"
   onClick="this.href=picklink()">randomly selected</A>
site from my list of favorites.</P>
Note
The this statement is a special value that tells JavaScript to reference the current object without having to worry about its exact name or location. In this example, this points to the link object associated with the link, and this.href indicates the href property of this object. Therefore, by assigning a new value to this.href, you change the destination URL of the link.

With the onClick handler set up, you need to alter the picklink() function. Because you are no longer physically writing anything onto the Web page, you can remove the document.write() function. But in its place, you need some way for the value of linkselect to be sent back to the this.href property.

You achieve this by using the return statement, which sends a value back from a function call, as shown here:

return linktext;

This return statement causes the function to return the value of linktext, which is the randomly picked URL that picklink() chose. Add the return line inside the picklink() function in place of the last document.write() line.

The Completed Exercise
If you examine the completed text for this new HTML document, you'll notice that it and Excercise 24.1 are similar, except for the removal of the inline <SCRIPT> tag and the replacement of document.write() with a return statement:
<HTML>
<HEAD>
<TITLE>Random Link Generator with events</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- the contents of the script need to be hidden from other browsers
function picklink() {
var linknumber = 4 ;
var linktext = "nolink.html" ;
var randomnumber = random() ;
var linkselect = Math.round( (linknumber-1) * randomnumber) + 1 ;
if ( linkselect == 1 )
   { linktext="http://www.netscape.com/" }
if ( linkselect == 2 )
   { linktext="http://www.webcom.com/taketwo/" }
if ( linkselect == 3 )
   { linktext="http://java.sun.com/" }
if ( linkselect == 4 )
   { linktext="http://www.realaudio.com/" }
return linktext;
}
function random() {
    var curdate = new Date();
    var work = curdate.getTime() + curdate.getDate();
    return ((work * 29 + 1) % 1-24 ) / 1024;
}
// End of script -->
</SCRIPT>
</HEAD>
<BODY>
<H1>My random link generator</H1>
<P>Visit a <A HREF="dummy.html"
   onClick="this.href=picklink()">randomly selected</A>
site from my list of favorites.</P>
</BODY>
</HTML>

Exercise 24.3: A random link generator using an array.

The only problem with the preceding example is the need to add another if test for each new link you want to include in your random list of favorites. To get around this difficulty and to streamline the appearance of the script considerably, JavaScript provides a mechanism that enables you to create lists of variables-or what are called arrays.

An array is a list of variables that are all referenced by the same variable name. For example, an array called mylinks[] could be used to contain a list of all the links used by the picklink() function. The value of each link in the list is then referenced by the placement of a numeric value inside the square brackets, starting from one: The first variable can be found with mylinks[1], the second with mylinks[2], and so on.

New Term
An array is an ordered set of values. You access a value in an array by a single array name and that value's position in the array. So, for example, if you had an array of your friends' names (called friends) containing the values "Bob", "Susan", "Tom", and "Pierre", friends[1] would be "Bob", friends[2] would be "Susan", and so on.

Note
Arrays in JavaScript operate somewhat differently from arrays that you've encountered in other high-level languages such as C++. In reality, the arrays used in this example are objects, but JavaScript enables you to treat them like arrays. Also, note that unlike arrays in many other languages, JavaScript arrays start from the index 1 rather than the index 0.

To take advantage of the possibilities offered by arrays, you first need to create a small function known as a constructor method. This function is needed because arrays are really objects. The MakeArray() constructor looks like this:

function MakeArray(n) {
this.length = n;
   for (var i = 1; i <= n; i++)
       { this[i] = 0 }
   return this
   }

This function creates an array with "n" elements, storing the number of elements in the zero position (thearray[0]). You need to include this function in your JavaScript code whenever you want to use arrays in a program. After the MakeArray() function has been defined, you can create the mylinks[] array discussed previously by writing the following statement in which value is the number of elements to be declared in the array:

mylinks = new MakeArray( value )
Note
There's a bit of confusion going on here with arrays and whether the index starts from zero or one. Technically, JavaScript arrays start from zero as in other languages. However, if you use MakeArray() to create arrays, the first element will be stored in index 1, with the number of elements at index zero.
In early versions of Netscape 2.0, an undocumented built-in array constructor was included as a part of the JavaScript language which creates arrays that really start at zero. To use this constructor instead of MakeArray(), you would write the following:
mylinks = new Array( value )
Depending on what you're used to, you may want to use the Array constructor rather than MakeArray in your programs. For this example, we'll use the "recommended" method of MakeArray() instead.

You can then fill the mylinks[] array with values by simply assigning them as you would any other variable. So, for example, in that random link exercise, you can add code to the <SCRIPT> section that creates an array with the number of links and then stores those link names into that array. Here's an example of an array with five elements with a URL assigned to each:

<SCRIPT LANGUAGE="JavaScript">
<!-- the contents of the script need to be hidden from other browsers

mylinks = new MakeArray( 5 ) ;

mylinks[1] = "http://www.netscape.com/" ;
mylinks[2] = "http://www.lne.com/Web/" ;
mylinks[3] = "http://java.sun.com/" ;
mylinks[4] = "http://www.realaudio.com/" ;
mylinks[5] = "http://www.worlds.net/" ;

With the list of URLs defined, we can modify the original picklink() function so that it selects a link by choosing from those included in the array, instead of by using a number of if tests. Here is the new code for picklink():

function picklink() {
   linknumber = mylinks[0] ;
   randomnumber = random() ;
   linkselect = Math.round( (linknumber-1) * randomnumber ) + 1 ;
   return mylinks[ linkselect ] ;
}

What exactly changed in this function? First, note the value assigned to linknumber. In the previous examples, you set this value manually (linknumber = 5, for example), but now you need to set it to the number of elements in the mylink[] array. You do this by using the value stored automatically by the MakeArray() constructor in mylinks[0]. This "zeroth" element contains the number of elements in the array.

Also, note that this version of picklink() is much smaller than the previous version because we pulled out all the if tests from the earlier exercises and put a single return mylinks[ linkselect ] statement in their place. This statement causes the value contained at mylinks[ linkselect ] to be returned, linkselect being a random number between 1 and the value of linknumber.

You can also consolidate the picklink() function even further by removing all the work variables and simply performing all the math inside the return statement, like this:

function picklink() {
   return mylinks[ ( Math.round( ( mylinks[0] - 1) * random() ) + 1 ) ] ;
}
The Completed Random Link Script with an Array
This final version of the script incorporates all the changes we've made in this exercise, including adding the MakeArray() constructor function, adding the creation of the array of links, and making the modifications to picklink():
<HTML>
<HEAD>
<TITLE>Random Link Generator with an Array</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- the contents of the script need to be hidden from other browsers

mylinks = new MakeArray( 5 );

mylinks[1] = "http://www.netscape.com/" ;
mylinks[2] = "http://www.lne.com/Web/" ;
mylinks[3] = "http://java.sun.com/" ;
mylinks[4] = "http://www.realaudio.com/" ;
mylinks[5] = "http://www.worlds.net/" ;

function picklink() {
   return mylinks[ ( Math.round( ( mylinks[0] - 1) * random() ) + 1 ) ] ;
}

function MakeArray( n ) {
this.length = n;
   for (var i = 1; i <= n; i++)
       { this[i] = 0 }
   return this ;
   }

function random() {
    var curdate = new Date();
    var work = curdate.getTime() + curdate.getDate();
    return ((work * 29 + 1) % 1-24 ) / 1024;
}
// End of script -->
</SCRIPT>

</HEAD>
<BODY>
<H1>My random link generator</H1>
Click <A HREF="dummy.html" onClick="this.href=picklink()">here</A>
to visit a randomly selected site from my list of favorites.
</BODY>
</HTML>
Note
To add new links to your list, simply increase the value assigned by new MakeArray( value ), and add the new links to the list following the array elements already defined.

Exercise 24.4: Form validation.

If you remember back to Chapter 18, "Basic Forms," you'll remember an example we created called "The Surrealist Census," shown in Figure 24.2. This form queried the reader for several different things, including name, sex, and several other bizarre options.

Figure 24.2 : The Surrealist Census.

What happens when this form is submitted? Assumedly, there would be a CGI script on the server side that would validate the data the reader entered, store it in a database or file, and then thank the reader for his or her time.

But what would happen if the reader didn't fill out the form correctly-if, for example, he or she hadn't entered a name or chosen a value for Sex? The CGI script could check all that and return an error. But because all this checking has to be done on a different machine using a CGI script and the data and the error messages have to be transmitted back and forth over the network, this process can be slow and takes up valuable resources on the server.

JavaScript allows you to do error checking in forms on the browser side before the form is ever submitted to the server. This saves both you and your reader time because everything is made correct on the reader's side, and once the data actually gets to your CGI script, it's guaranteed to be correct.

Let's take a look at how The Surrealist Census would be validated with JavaScript.

Whenever you click the submit button of a form, two events are triggered by JavaScript and Netscape: an onClick event and an onSubmit event. The one you're interested in is the onSubmit event, to which we'll attach a JavaScript function. Then, when the onSubmit event occurs, the JavaScript function will be called to validate the data.

To attach a JavaScript function to the onSubmit event, you define onSubmit as an attribute of the <FORM> tag, like this:

<FORM METHOD="POST"
      ACTION="http://www.mcp.com/cgi-bin/post-query"
      onSubmit="return checkform( this )">

In this example, the value assigned to onSubmit is a call to a function named checkform()-which we'll define in a bit. But first, the return statement at the beginning of the onSubmit field and the this statement inside the checkform() function's parentheses need some further explanation.

First, the this statement. Whenever you call a function, you can send it a list of parameters such as numbers or strings or other objects by including them inside the function's parentheses. In the preceding example, the statement this is used to pass a reference to the form object associated with the current form.

Second, the return statement. This statement is used to transmit a value back to the internal Netscape routine that called the onSubmit event handler. For example, if the checkform() function returns a value of false-after evaluating the form-the submission process will be halted by the return command transmitting this false value back to Netscape. If the return command was not included, the false value could be sent back to Netscape, and the submission process would occur even if problems were detected by the checkform() function.

The Validation Script
As you've done before, define a <SCRIPT> tag inside the <HEAD> block and declare checkform() as a function. But this time, you also need to define a variable to receive the form object sent by the calling function, as mentioned previously. The code for the function declaration looks like this:
<SCRIPT>
<!-- start script here
function checkform( thisform ) {
In this example, the object representing the current form is given the name thisform by the checkform( thisform ) statement. By accessing the thisform object, you can address all the fields, radio buttons, check boxes, and buttons on the current form by treating each as a sub-object of thisform.
This having been said, the first test you want to make is whether a name has been entered in the Name text box. In the HTML code for this form, the <input> tag for this field was assigned a NAME attribute of theName, like this:
<input TYPE="TEXT" NAME="theName">
This is the name you use to reference the field as a sub-object of thisform. As a result, the field theName can be referenced as thisform.theName and its contents as thisform.theName.value.
Using this information and an if test, it's a simple process to test the contents of theName to see whether a name has been entered, by writing this:
if ( thisform.theName.value == null || thisform.theName.value == "" ) {
      alert ("Please enter your name") ;
      thisform.theName.focus() ;
      thisform.theName.select() ;
      return false ;
   }
Note
The || symbol shown in the if test of the previous example tells JavaScript to perform the actions enclosed by the braces if either of the two tests is true. As a result, the || symbol is commonly know as the OR operator.

In the first line, thisform.theName.value is tested to see whether it contains a null value or whether it is empty (""). When a field is first created and contains no information at all, it is said to contain a null; this is different from it being empty or containing just spaces. If either of these situations is true, an alert() message is displayed (a pop-up dialog box with a warning message), the cursor is repositioned in the field by thisform.theName.focus(), the field is highlighted using thisform.theName.select(), and the function is terminated by a return statement that is assigned a value of false.
If a name has been entered, the next step is to test whether a sex has been selected. You do this by checking the value of theSex. Because all the elements in a radio button group have the same name, however, you need to treat them as an array. As a result, you can test the status value of the first radio button by using testform.theSex[0].status, the second radio button by using testform.theSex[1].status, and so on. If a radio button element is selected, the status returns a value of true; otherwise, it returns a value of false.
Note
Unlike arrays created using MakeArray, array elements in forms start from index 0.

To test that one of the theSex radio buttons has been selected, declare a new variable called selected and give it a value of false. Now loop through all the elements using a for loop, and if the status of any radio button is true, set selected = true. Finally, after you have finished the loop, if selected still equals false, display an alert() message and exit the function by calling return false. The code required to perform these tests is shown here:
var selected = false ;
for ( var i = 0; i <= 2 ; ++i ) {
   if ( testform.theSex[i].status == true )
      { selected = true }
   }
if ( selected == false ) {
   alert ("Please choose your sex") ;
   return false ;
}
If both of the tests pass successfully, call return with a value of true to tell Netscape that it can proceed with the submission of the form, and finish the function's definition with a closing brace:
   return true
}
The Completed Surrealist Census with JavaScript Validation
When the JavaScript script discussed in this section is integrated with the original Surrealist Census HTML document from Chapter 18, the result is a Web form that tests its contents before they are transmitted to the CGI script for further processing. This way, no data is sent to the CGI script until everything is correct, and if there is a problem, Netscape takes care of informing the user of the difficulty (see Figure 24.3).

Figure 24.3 :An Alert message.

So that you don't need to skip back to the exercise in Chapter 18 to obtain the HTML source used when creating the form, here is the completed form with the full JavaScript code:
<HTML>
<HEAD>
<TITLE>The Surrealist Census - With JavaScript</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- start script here
function checkform( thisform ) {
   if (thisform.theName.value == null || thisform.theName.value == "" ) {
      alert ("Please enter your name") ;
      thisform.theName.focus() ;
      thisform.theName.select() ;
      return false ;
   }
   var selected = false ;
   for ( var i = 0; i <= 2 ; ++i ) {
       if ( thisform.theSex[i].status == true )
          { selected = true }
       }
   if ( selected == false ) {
      alert ("Please choose your sex") ;
      return false ;
   }
   return true
}
// End of script -->
</SCRIPT>
</HEAD>

<BODY>
<H1>The Surrealist Census</H1>
<P>Welcome to the Surrealist Census. Please fill out the following
form to the best of your abilities.</P>
<P>Use <STRONG>Submit</STRONG> to submit your results.
<HR>
<FORM METHOD="POST"
      ACTION="http://www.mcp.com/cgi-bin/post-query"
      onSubmit="return checkform( this )" >
<P>
<STRONG>Name: </STRONG>
<input TYPE="TEXT" NAME="theName">
</P>
<P>
<STRONG>Sex: </STRONG>
<input TYPE="RADIO" NAME="theSex" VALUE="male">Male
<input TYPE="RADIO" NAME="theSex" VALUE="female">Female
<input TYPE="RADIO" NAME="theSex" VALUE="null">Null
</P>
<P>
<STRONG>Contains (Select all that Apply): </STRONG><BR>
<input TYPE="chECKBOX" NAME="humor">Vitreous Humor<BR>
<input TYPE="chECKBOX" NAME="fish">Fish<BR>
<input TYPE="chECKBOX" NAME="glycol">Propylene Glycol<BR>
<input TYPE="chECKBOX" NAME="svga">SVGA Support<BR>
<input TYPE="chECKBOX" NAME="angst">Angst<BR>
<input TYPE="chECKBOX" NAME="catcon">Catalytic Converter<BR>
<input TYPE="chECKBOX" NAME="vitamin">Ten Essential Vitamins and Nutrients<BR>
</P>
<P>
<input TYPE="SUBMIT" VALUE="Submit Your Votes" >
<input TYPE="RESET" VALUE="Clear Form" ></P>
</FORM>
<HR>
</BODY>
</HTML>

Summary

JavaScript offers many exciting new possibilities for Web developers. In this chapter, you had the opportunity to explore several possible applications of JavaScript, including generating bits of HTML code and verifying form data.

But JavaScript is not the only way to write code for Web pages. Java-the big brother of JavaScript-adds even greater flexibility and capabilities to the Web publication environment. Tomorrow, you'll learn about how Java works and how it differs from other languages, including JavaScript.

Q&A

QIs there actually any difference between JavaScript and LiveScript?
AYes there is, and as the JavaScript standard develops, the differences will increase considerably. For example, LiveScript was case-insensitive (uppercase and lowercase were the same thing), whereas JavaScript is case-sensitive. Currently, LiveScript code runs on Netscape 2.0, but you should make the effort to update any old code of JavaScript as soon as possible.
QI'm really confused. Once and for all, do JavaScript arrays start from 0 or from 1?
AJavaScript arrays start from zero as in other languages. However, if you use Netscape's recommended method of creating arrays with the MakeArray() constructor, you'll end up with an array that starts with 1 (the number of elements in the array is stored in element zero). This is enormously confusing; arrays should consistently start from either zero or one, but not both.
QI like working in JavaScript; it's simple and easy to understand. It seems to me JavaScript would make a great language for CGI or for other programs on the server side. Can I do that?
ANetscape had the same idea! Server-side JavaScript is one of the features being included in the newer Netscape servers-which will most likely be out by the time you read this-which have many features for using JavaScript as a CGI language and also for pre-processing HTML files before they are sent to the browser.