www.htmlgoodies.com/primers/jsp/article.php/3655571

Back to Article

The JavaScript Diaries: Part 1
By Lee Underwood
January 23, 2007

JavaScript is a versatile language. It can be used to create menus, validate forms, provide interactive calendars, post the current day's headlines, produce background effects on a Web page, track a visitor's history on your site, and play games, among many other things. That's probably why it's one of the most popular languages on the World Wide Web.

Netscape created JavaScript in 1995. Originally called "LiveScript," it was designed to make Web pages more interactive. In the beginning the language was plagued with security problems which, for the most part, have been overcome. The current version of JavaScript is 1.5.

Because of its usefulness, I've long thought about whether I should learn JavaScript programming or not. One of the main reasons I kept putting it off was the availability of free, existing scripts. 'Why re-invent the wheel?', I kept asking myself. If I could spend a few minutes searching my favorite sites for scripts (such as JavaScript Source and ScriptSearch), why should I spend my time learning how to write them? And so it went on for several years.

Today, there is a lot more that JavaScript can do and as a result, I've decided the time has come to learn it. My intention is not to become a JavaScript guru or programming genius but to be able to write scripts that I can use in my work, and perhaps share with others.

I know that I'm not the only one who feels this way and yet, learning JavaScript seems to be a monumental task. When you look at some of the JavaScripts out there, they can seem pretty intimidating. And that's true with most things that are new. Remember the first time you viewed the source code of an HTML document or took a look at a style sheet? Whoa! I'm sure you felt overwhelmed..

Still, there is only one way to get started; you just do it! To make the process easier, I decided we could do this together.As I study the JavaScript language, I will share what I have learned with you, the reader. Our goal in this study will be to learn how to competently write useful JavaScripts (these installments will be published on a bi-weekly basis).

To give you some some insight into my background, I'm no different than most of you. I'm not a programmer nor do I have any high-level technical degrees. I have learned HTML, XHTML, and a few other things on my own using books, Web sites, existing examples, and by asking questions. That's how many of the people who design Web sites today got their start.

If you have any problems or questions that are beyond my scope of knowledge, you can visit the JavaScript forums over at WebDeveloper.com. They should be able to answer all your questions. In fact, the moderator of the forum is our own Jonathan Fenocchi. He writes a regular column for us here at WebRef.

For instructional purposes, I will be using the following two references:

In addition, I will be using a few other books and Web sites that will help in our understanding of this intriguing language.

Before We Begin

There are a few things you will need before we begin our study. One of them is a basic knowledge of HTML/XHTML. While you don't need to be an expert, you will need to know the basics of using HTML elements and attributes. JavaScript can be used to dynamically create Web pages and a general knowledge of HTML is essential. A little knowledge of CSS won't hurt either.

Another thing you will need is a text (ASCII) editor. JavaScript code is just plain text so any good text editor will work well.. There aren't too many JavaScript editors out there right now (although I am reviewing one as we go through this process). There are, however, several good text editors. One editor I am very familiar with is NoteTab (which comes in three versions). I use it for all my HTML and text editing. You can read a review I wrote about it on the Web Developer's Virtual Library (it's a few years old but there has only been one minor upgrade since then). You can also use WordPad or Notepad. It would be best not to use a word processor or a WYSIWYG HTML editor as they tend to add a lot of extra code that will cause the scripts to fail.

It's assumed that you have a Web browser (a.k.a. "client", "user agent"). You should test your scripts in both Internet Explorer and Netscape. It would also be wise to test them in Firefox and Opera, as these browsers are becoming more popular. There are other browsers also but these are the main ones being used today. Safari is another popular browser but it is used on the Apple system, which makes it hard to test using a Windows-based system.

Now let's get started!

An Introduction

First, there are a few things you need to understand.

JavaScript is not Java
Java is a compiled language. This means that the Java code must be transformed ("compiled") into a high-level programming language before it can run.

JavaScript is an interpreted language. It doesn't need to be compiled before it is run. In an interpreted language the instructions are parsed (divided into small components that can be analyzed). For instance, as the browser "reads" this page, it breaks down each of the page's components into individual components and interprets each component as it moves down the page. In linguistics it means to divide language into small components that can be analyzed. For example, parsing this sentence would involve dividing it into words and phrases and identifying the type of each component (such as a verb, adjective, or noun).

JavaScript can either be client-side or server-side
This refers to the place where the script is processed. We will be dealing with client-side scripts. This means that the script is processed ("runs") in the client (e.g., browser). The script will be processed directly in the browser without having to send or receive data to or from the server. Most JavaScript is client-side.

JavaScript is an object-based scripting language
Object-based means that JavaScript sees the existing data structure as objects. A JavaScript object is merely a thing. It's like the objects around us. In addition, each object has properties. For example, I have two cats. They are the objects. They have fur, ears, and tails. These are the properties (more on this later.)

JavaScript is cross-platform
The code will run on a wide variety of computer platforms. This means that users with all kinds of computers using different kinds of operating systems are able to obtain the same results as everybody else.

JavaScript comes in different 'flavors'
  • JavaScript: This was the name given by Netscape, who invented it. It was first used in Netscape 2.0. This is the most popular version of the language and is what we will be learning. The current version is 1.5.
  • JScript: This is the scripting language invented by Microsoft to compete with JavaScript.
  • ECMAScript: The de facto international standard for JavaScript. This standard covers the core of the language.
Since version 4 of the Netscape and Internet Explorer browsers, JavaScript and JScript have had the same core functions. This means that they both utilize the core language features included in the EMCA standard. While IE recognizes both JScript and JavaScript, Netscape does not. However, since the tags are essentially the same, if the scripts are written in JavaScript, they will run on both browsers, for the most part. There are some differences between the JavaScript and JScript codes, but later on, we'll look at ways to overcome that within the context of the script itself.

A Few Things You Need to Remember

When writing scripts it's best to get in the habit of entering a semicolon at the end of each statement (e.g. var x = range;). While it's not required, it can help to eliminate errors.

There is no "proper" format for writing scripts. However, breaking up lines and indenting some of them does make it easier to read and debug. For instance, the layout here:

function getObject(obj) {
  var theObj;
  if(document.all) {
    if(typeof obj=="string") {
      return document.all(obj);
    } else {
      return obj.style;
    }
  }
  if(document.getElementById) {
    if(typeof obj=="string") {
      return document.getElementById(obj);
    } else {
      return obj.style;
    }
  }
  return null;
}

is much easier to read than this one:

function getObject(obj) {var theObj;
if(document.all) {if(typeof obj=="string") {return document.all(obj);}
else {return obj.style;}}
if(document.getElementById) {if(typeof obj=="string") {return document.getElementById(obj);}
else {return obj.style;}}return null;}

You also may need to edit a script several months after writing it. If it's cleanly formatted it will be an easier job. In addition, if someone else uses your script it will make it easier for them to understand how the script works. For the most part, JavaScript ignores tabs and spaces. A little later on in our study we will look at when it is important to pay attention to these "whitespaces."

It's also a good idea to add comments to your scripts, especially if the script is long. There are two methods for adding comments. For a single comment line use two forward slashes, "//". You can even do this on the same line as the code:

// This whole line will be ignored by the JS interpreter

var myOldCar = Ford     // The first part will be interpreted; this part will be ignored.

If you need to comment out several lines, you would begin with a forward slash and an asterisk, "/*", and end with an asterisk and a forward slash, "*/". For example,

/* All of this, all three lines,
will be ignored in their entirety
by the JavaScript interpreter */

Just a couple of cautions when placing comments in a script. Make sure you don't nest comments (one inside of another) and keep the comments concise to save download time. Everything you write in a script is downloaded to the browser. Although the comments are not viewed by the user, they still take up precious bandwidth and RAM.

Also, remember that JavaScript is case-sensitive. This means that it sees myAuto and myauto as two completely different variables. Be very careful when entering code. Using the wrong case will cause your script to fail.

Where Does the Script Go?

There are three places where a script can be located:

  1. In the top section of the page ("head"), between the <head> and </head> tags;
  2. In the middle section of the page ("body"), between the <body> and </body> tags; or
  3. In a separate file.

Placing the Script on the Page

When the script is placed on the page, it is located between a set of container tags that look like:

<script type="text/javascript">
<!--
... The script is placed here ...
//-->
</script>

The opening tag, <script type="text/javascript">, tells the browser:
  • it has encountered a script;
  • it is in text format; and
  • it is to be interpreted as JavaScript.
Note: There are several different ways to write this, but the W3C recommends the method shown here so that's what we'll use).

The next line, <!--, is the opening comment tag. It's used to hide the code from older browsers. The actual script starts on the third line. After the script ends, the comment tag is closed, //--> and the </script> tag tells the browser that the code is finished. The <script type="text/javascript"> and </script> tags are known as "container" tags because they "contain" the script within them.

Placing the Script in an External Page

When the script is located in an external file, the opening and closing tags shown above are not included. Only the script itself is included in the file. The file should have an extension of ".js." The HTML page would then contain a link to the JavaScript file, which would look like this:

<script type="text/javascript" src="/javascript/scriptfile.js"></script>

The opening tag, <script type="text/javascript" src="/javascript/scriptfile.js">, tells the browser:
  • it has encountered a script;
  • it is in text format;
  • it is to be interpreted as JavaScript; and
  • the script is located in an external file located at the given URL.
The closing tag, </script>, tells the browser that the code is finished. Nothing should be written between the opening and closing tag.

The link is usually located in the head of the document. In some cases it may be necessary to locate it within the body. It will depend on the script.

If the script is small and used only once, it's usually best to put it in the actual document. Otherwise, it's preferable to place the script in an external file.

By placing the script in an external file, it can be used on other pages without having to duplicate the code. The browser will then cache the script and use it on the other pages, making them to load faster. Using an external file also makes it easier if changes need to be made to the code. You only have the one file to change instead of making changes to each individual page.

Reserved Words

There are 59 "reserved" words. These are words that are used to give instructions to the JavaScript interpreter. They cannot be used for anything else and are listed below. We'll be looking at them in more detail as we use them. For now, just remember not to use them as variables.

abstractbooleanbreakbyte
casecatchcharclass
constcontinuedebuggerdefault
deletedodoubleelse
enumexportextendsfalse
finalfinallyfloatfor
functiongotoifimplements
importininstanceofint
interfacelongnativenew
nullpackageprivateprotected
publicreturnshortstatic
superswitchsynchronizedthis
throwthrowstransienttrue
trytypeofvarvoid
volatilewhilewith 

Wrap-Up

That should just about do it for this installment. So far we've:

  • gained a little insight into the history of JavaScript;
  • found out what we needed to write the scripts;
  • gained some insight into what JavaScript is and what it isn't;
  • learned how to format a script;
  • learned how to make comments in a script;
  • and found out where to place a script in relation to the Web page.

Next time we'll be looking at variables and writing our first script. Remember, if you have any questions, you can send them to me or visit our JavaScript forums.

Review Questions

Answers to these questions will be given in the next installment (these questions are for your benefit. I won't be collecting your answers).

Multiple Choice
  1. JavaScript is:
    1. an interpreted language
    2. a compiled language
  2. JavaScript is:
    1. subjective
    2. object based
    3. objective
  3. To comment out a line:
    1. Precede it with an asterisk, i.e. "*"
    2. Precede it with an asterisk and a forward slash, i.e. "*/"
    3. Precede it with two forward slashes, i.e. "//"
True or False
  1. JavaScript can only run on Windows.
  2. Semicolons are optional at the end of a statement.
  3. JavaScripts should not be formatted.
  4. It is best to place the JavaScript on each separate page.
Essay
  1. What is JavaScript, JScript, and EMCAScript?
  2. What is the purpose of the <script type="text/javascript"> tag? Explain how it works.
  3. What is the purpose of the <script type="text/javascript" src="/javascript/scriptfile.js"> tag? Explain how it works.
  4. What extension should be used for an external JavaScript file?
  5. What are "reserved words" used for?

This article originally appeared on WebReference.com.