Beginner's JavaScript

Java without all the tedious programming? Not quite.

If you've seen all the interesting things that the world of Java is bringing to the Web, but are afraid of trying to learn a programming language this complex, you should consider JavaScript, a joint effort from Sun and Netscape. Among the variety of amazing features that Netscape Communications Corp. includes in version 2.0 of its browser is the client-side scripting feature initially introduced as LiveScript. Renamed JavaScript, this language is an offshoot of the Netscape-Sun Java project; the members of the Sun Java-team described this scripting system, before it was available to the public, as a rapid means of writing small useful scripts and applets. Netscape's directional focus they underwent last December introduced a whole new set of development partners interested in building applets and applications for the new version.

In this inaugural issue of JavaWorld, we will introduce JavaScript to interested novices with a short series of articles covering technical aspects of JavaScript and its functionality. Since I would rather we not try to fly before we can walk, I will first go over the very basics of the language and its structure. We will do very simple examples that you can add to your page and then try some more interesting projects in future articles.

Another Java?

Contrary to some beliefs, JavaScript is not merely a decaffeinated version of Java for beginners and novices. The LiveScript/JavaScript animal is quite separate from direct Java applets and applications since it provides the functionality for a different niche in the market. It is, primarily, a solution for Client-side APIs in Netscape Navigator 2.0. The discussion of the use of Client-side Application Programming Interfaces (APIs) in the world of the Web, once Server-side APIs had caught a hold, is still ongoing. The push toward moving the application processing from an already weighted server to the local user's interface came with the improvements in end-user desktop technology, both in hardware and software. With the increase from 486-based to Pentium-based and 68000-based to PowerPC-based PCs, the ever dropping price of secondary storage and memory, the technical demands of the average user are also increasing.

JavaScript provides this client-side API to take care of the nuisances of static Web text. Netscape is also working on creating a server-side system with JavaScript, possibly with a link to the Common Gateway Interface (CGI) for backward compatibility. It is currently available on all the Netscape 2.0 beta version browsers and runs on all the different platforms. Note to Mac users: the fact that JavaScript is available in the Mac browser doesn't mean that your Mac Netscape 2.0 browser can do Java applets. The Macintosh and Windows 3.1 versions of the Netscape 2.0 still do not support Java.

Java-lite

Formerly known as Java-lite or Mocha internally, JavaScript takes away some of the tedium involved in writing heavy-duty Java applets to do simple calculations or browser control functions. The most obvious difference between the two is that JavaScripts are immediately interpreted by the browser from the source code, whereas Java applets need to be precompiled into a class before actual use. For the lay person this means that the scripts may run slower; each line is interpreted separately, usually one keyword and parameter combination at a time, rather than having faster compiled and code that can be immediately executed by the Java runtime environment within the browser.

Although you have to give up some object-oriented features available in Java, you still have objects with their methods and variables providing the necessary utility. You can define objects but not classes of objects. The difference between an object and a class, in layspeak, is the difference between a building and its architectural plan; once you have a building, you can use it until its end; but if you have the building's architectural plan, you can build other buildings just like it or make major modifications to it.

You also have to give up object inheritance. In our building analogy, with classes and inheritance you can effectively make modifications to the architectural plan to make a better building, or one more suitable for its use. Classes and inheritance exist to facilitate and improve the functionality and reuse of objects. In short scripts, you probably will not reuse an object too often so it is not really necessary. JavaScript provides loose type declaration for the lazy.

Programmers in the classic C, Pascal, and even Java worlds are familiar with strong type declarations where you have to specify that a variable is a string, an integer, etc. In JavaScript, similar to how it works in the Perl language, you simply use a variable as necessary and it is up to the programmer to remember not to suddenly change a string into an integer or boolean. This lenient factor is partially due to the fact that the designers do not expect users to write too intensively detailed a program. For run of the mill scripting, it is easier to live without strong type declarations.

True Java applets do not generally interact with the HTML of a Web page. Each applet is limited to a subarea of the page. Although an applet can be made to communicate with several other applets on the same page, it cannot, however, change the text of the same HTML page in which it is located. Javascript, on the other hand, was created solely to allow HTML writers to allow different HTML tags and elements to interact with each other. An input box in one HTML form can modify the HTML information inside another HTML page.

In truth, there are actually ways of controlling your browser from within Java applets. However, to do simple things like calculations within forms, changing other frames within the browser, etc., takes a substantial amount of coding for a simple task. Javascript was made to allow HTML writers to implement such functionality without spending hours upon hours writing Java code.

Another important difference, although not directly stated, is that you do not have the large set of class libraries that you can use with Java. This limits the scripts to simple calculations and event processing. For example, you cannot start a separate network connection within JavaScript and download a new class over the network into your hierarchy to build upon your basic browser's ability dynamically over the network; this is something you can do with Java, on the other hand.

So what can you do with it?

Now that you know the what and why, we will continue in the next issue with the when and the how. As we mentioned, JavaScripts can quickly deliver interactive Web forms with a greater degree of efficiency. Previously, using server-based scripts, the programmer had to develop a series of Forms and scripts, or multiple steps within the same script, to perform error-checking and correction. With JavaScript, error-checking can be quickly taken care of with the built-in event-handling mechanisms based upon user interaction with the Web form. With JavaScript you can also develop dynamic Forms that change on the user's screen depending upon the HTML checkboxes, radio buttons or other input fields that you fill in.

JavaScript also can be used for small applets that handle quick functions or calculations that would otherwise require the painstaking aid of server-based scripts. For users who do not have direct access or control of the server to configure and develop server-based scripts, this alternative scripting mechanism saves the day. Netscape 2.0 HTML tags used for Forms, including the FORM, INPUT, and TEXTAREA, have been "enhanced" to allow event-driven activities such as mouse clicks, focus, entered text, etc., to call scripts within the document. Netscape also has created a new tag known as SCRIPT. All information between the open and close SCRIPT tags is interpreted as JavaScript. This tag pair can be placed anywhere in the BODY section of the HTML file, or in the HEAD section. If the script tag-pair is placed in the HEAD section, the code within that script is executed before the body of the HTML page is completely downloaded. This allows interpretation of any code to be done before the user enters any text into the form itself. so events can be handled properly.

You may in turn want to add scripts within the body of the text if for example, you wish to create a dynamic form displaying different form tags or HTML code depending upon what you enter into the earlier form elements.

The script need not be located within the same HTML file. It can be located elsewhere and downloaded separately from the HTML file, the same way images are kept separately. Unfortunately, at the time of this writing (using 2.0 Beta 6), this could not be tested because it has yet to be implemented by Netscape.

The First JavaScript example shows an example of the of the SCRIPT tag with direct code immediately following it.

<HTML>
<HEAD>
<TITLE>My First JavaScript Page</TITLE>
<SCRIPT LANGUAGE="Javascript">
<!--
document.write("This text will appear before the actual body of the HTML 
page.");
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3> This is my first JavaScript Web page! </H3>
</BODY>
</HTML>

First JavaScript example

If you look at the HTML code, you will notice some things that may seem peculiar at first. For example, the HTML comment tag "<!--" encloses the body of the script itself. This is done so that other non-Netscape browsers don't confuse the JavaScript code as text and actually display it on the screen as part of the text of the page. If you are using an older beta version of Netscape 2.0, before the beta 5 release, the code will not work unless you change the tag from LANGUAGE="Javascript" to LANGUAGE="Livescript". LiveScript was the precursor name to JavaScript; the older betas do not understand the new name, of course. You should use LANGUAGE="Javascript" from now on.

In this example we do something simple: Write a line of HTML text into the page. No one would actually do just that unless they were necessarily trying to be difficult. We offer this example first because we have yet to get to the constructs and syntax of the language itself. If we wanted to keep the actual code elsewhere, we would change the SCRIPT tag to as shown below

<SCRIPT LANGUAGE="Javascript" 
SRC="http://www.mydomain.com/myscript.js">
</SCRIPT>

This feature will not be available until future versions (probably version 2.1, unfortunately), so just keep it in mind. With this method of locating code elsewhere, the HTML file is much cleaner and you do not need to add the HTML comment tag to hide the script from other browsers; they simply won't understand the SCRIPT tag and will ignore it completely. Here's another small note about these tags: we named the file with the extension .js as opposed to .java. Although it is not really necessary to give an extension, it is good practice, and using .js instead of .java (the required extension for true Java code) will reduce confusion. Note that you cannot use a compiled Java applet as a JavaScript; despite some similarity in name and structure, Java and JavaScript are two distinct languages.

Now let's move on with the actual syntax of JavaScript.

Syntax

If you have seen C, C++, or even Java code before, you may be familiar with the syntax already. The language has a set of reserved words that act as the control mechanisms of the language. In addition, there is a set of built-in functions that perform tasks like writing a line of text, doing mathematical calculations and the like. You can create variables that store data that can be modified or reused. Only a handful of raw data types are used.

Although you can essentially have one monolithic set of instructions, several hundred lines long, to do an entire program, most programmers break their code into smaller useful sections. These smaller pieces of code can help you perform groups of instructions at a time by invoking just one function. It saves you time from rewriting the same instructions over and over within the program. JavaScript provides these sets of code as functions that can be executed as a single unit. Within the block of the function is a set of JavaScript that performs everything needed by that function. None of the code within a function is executed until the function is actually called elsewhere in the code.

Reserved characters and operators

A good number of the non-alphabetic characters in the ASCII set are used as operators within the language. These operators perform specific simple mathematical, and logical functions. An operator usually has two other components: the lvalue (the value to the left of it) and the rvalue (the value to the right). C and C++ programmers will be glad to know that the operator sets are almost identical to their own.

1 2 3 Page 1
Page 1 of 3