Chapter One
Stuff Ya Just Gotta Know


Well, you got this far... I guess you're serious about learning this stuff! Hunh! Very interesting...

You can just skim-read through this chapter. The stuff you'll find here pertains to the basic rules you'll have to observe -- even to write ugly JavaScript.

No need to take notes. There ain't gonna be a quiz. But pay attention! Because if you ignore any of these rules, your scripts will bomb. How to Tell the Web Browser that You are Using JavaScript

I really hope you have at least a basic understanding of HTML. JavaScript and HTML work together. If you don't know how HTML works, you'd better stop right now and go learn a bit about how HTML controls what your Web Browser displays on screen.

If the only HTML you do is to fire up one of the HTML generation applications, you don't know enough.

One further aside - at least as of the time this is being written, do not ever let Front Page® see your JavaScripts. Can't tell you how many emails I've gotten where this HTML generator has "fixed" JavaScript past all possible redemption.

HTML is used to tell the Browser that the portion of text within the tags <B> and </B>, for example, is to be displayed in Bold Face type.

Similarly, you must tell the Browser that you are using JavaScript.

The HTML tags you use are <SCRIPT> and </SCRIPT> like this:

<SCRIPT LANGUAGE="JavaScript">
</SCRIPT>

Because many browsers can't do JavaScript, you need to "hide" the script from them. You do this with the HTML comment code.

Comments in HTML look like this:

<!-- This is an HTML comment -->

So, it is important that you place the entire script you are preparing inside the comment tags. The JavaScript compiler that puts your script together when the HTML page is loaded for a visitor to your pages "knows" that it can read the script, even though it is inside an HTML comment string, so it ignores the tags so long as they appear within the tags.

JavaScript uses different symbols for comments (stuff that it should ignore) than the ones you are accustomed to using in your HTML.

The first of these is the single line comment symbol, which is two slashes (//) appearing any where from the beginning to the end of a line, like this:

// This is a comment in JavaScript

Single line comments can be on their own individual line, or can appear on the same line as executable code, so long as they are the last thing on that line. (The compiler ignores everything after the // to the end of that line)

Sometimes, however, you may want to write some comment notes to yourself in your script that are longer than will fit on one line or at the end of a line.

The multiple line comment symbol commences with slash-asterisk (/*) and ends with asterisk-slash (*/) It hides everything contained between the two symbols from the compiler and looks like this:

/* This is a multiple line comment
   in JavaScript which will be
   totally ignored by the JavaScript
   compiler. */

Once you understand this difference in comment symbols, it will be more understandable to you why all JavaScripts should have this same general appearance:

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from JS-Impaired Browsers
/* Your own JavaScript will appear in
  this area. */
// End Hiding -->
</SCRIPT>

JavaScript Needs Returns

Experienced HTML programmers know that, for the most part, HTML ignores carriage returns or line breaks (with the exception of text within the <PRE></PRE> and <TT></TT> tags and images stacked side by side)

This is not true for JavaScript. It is supposed to ignore returns and linefeeds, relying instead on semicolons and other symbols to tell it that a particular command has been completed.

In practice, it is really easy to forget a semicolon at the end of a line, so the compiler does read returns, so that your code won't be "broken".

Important Rule:

The JavaScript compiler can not handle long lines. It may well "lose" everything on a given line after the fiftieth or sixtieth character.

So the first good rule for you to remember when writing your own scripts is this:

Keep your code lines short.

From time to time, you may need to use very long lines. When that happens, you need to "break them up" by "adding lines together" using a plus sign. But more about that later...

Where to Put Your Scripts in HTML

Routines that will be executed upon a given action by the visitor to your page, such as clicking a SUBMIT button or on an image map or perhaps simply moving his/her cursor over a link should be "preloaded" in your HTML document.

How do you do this? You put that portion of your JavaScript inside the <HEAD></HEAD> tags and before the <BODY> tag.

Doing this will insure that the script is preloaded (compiled) and "ready to fire" the instant that the visitor performs some action on your page.

You may sprinkle additional scripts throughout your HTML, as well. Generally, it is better to use these to "call" routines that were "preloaded" between the <HEAD></HEAD> tags, rather than having them contain long routines of their own.

But JavaScript will usually "forgive you" if you forget and put a long, kleugey routine outside the "preload" area.

Recognizing Routines and Subroutines

Okay. It's time to bite the bullet and learn one techie term. It is called "function". Think of it as a way of labeling a section of your code as a routine or a subroutine that will never execute unless it is "called".

A function will look something like this:

function doSomething(){
// Some code lines here
}

This function may be a routine or a subroutine that does anything you want done, whether it is to perform a calculation, to obtain a random number, to read a database or to print something to the screen.

You name the function with your own label. Its name may not begin with a number, but may include underscores if you wish.

When you make up names for your functions, it will help you later if you use names that may give you a clue as to what the routine is supposed to do.

You could, for example, name a given routine any of the following:

function do_something(){
// Some code lines here
}

function doSomething(){
// Some code lines here
}

function ds(){
// Some code lines here
}

function d(){
// Some code lines here
}

Notice that the name you give the routine is followed by parentheses -- () -- and then a curly bracket -- {

Then, after the actions you want performed have been specified, it is ended with the closing curly bracket -- }

This routine or subroutine is executed (performed) every time you "call" it with the single JavaScript line:

do_something();
or
doSomething();
or
ds();
or
d();
(using the function names from above)

JavaScript will then do everything you have specified between the curly brackets of that function before doing anything else.

Those parentheses following the call of doSomething(); are important. If you forget them, the script will not compile properly.

Finally, JavaScript is case sensitive, so if you name your function "now()", and then try to have it executed by calling: Now(); the script will not find a function with that name and will give you an error message. The upper and lower case letters must be exactly the same.

Variables - What are they?

The word "variable" should not intimidate you. It is a techie word that means "something that changes - or can be changed".

It can be a number, a word or a sentence or some combination of those.

In JavaScript, you may define a variable by using the codeword var. And you define it by making it equal to something. For example, within a JavaScript, if you say:

var x=1;
var y=2;

you've already done some programming.

You have defined x as being equal to 1 and y as being equal to 2.

These are known as numerics. Notice that you don't put quotes around the 1 and 2. You just use the number, and this tells JavaScript that you want it to be treated as a number - always.

These are called variables because they can change, if you want them to.

For example, after defining these two variables, later on in your program you might have a statement like:

x=x+y;

which would change the variable

x to now be equal to 3 -- (x = 1 + 2 = 3)

Too simple, right? Well, that's what programming is all about -- thinking simple. Because computers are really dumb. Ya gotta tell them what to do in little tiny steps, so they can do what ya want 'em to.

The irony is this: once you've given your computer all the tiny steps, it can perform them faster than you ever could.

I've also sneaked in another programming requirement that you probably didn't notice. That is the semi-colon.

In all of the definitions above, you'll see that there is a semi-colon at the end of each line.

The semi-colon tells JavaScript that you are done with that line.

You can get by without it, but don't. Always end your statements with a semi-colon. It'll keep you out of trouble.

But do not put semi-colons after the function name nor immediately after either of the curly brackets.

Strings: What the Heck Are They?

Another new word to learn. That word is "string".

A string variable is a sentence, a phrase or most anything comprised of a bunch of letters and/or numbers.

And whereas all numerics are defined without quotes, all strings must be defined with quotes.

By the way, computers love strings and process them more efficiently than numbers. Why? Because most string operations only require register offsets. But numerics require more complicated processor operations.

Single Quotes ('), Double Quotes (") and Backslashes (\)

If you are new to programming, you will need to take the time to understand how to use single quotes, double quotes and backslashes.

Strings must be enclosed in either single or double quotes:

var str1="Now is the time"; // OK!
var str2='Now is the time'; // OK!

The JavaScript compiler doesn't care which you use -- the two definitions above are equivalent -- but you must be careful when the string you are defining has a quote or double quote within its contents:

var str1="That's life!"; // OK!
var str2='That's life!'; // ERROR!

(The compiler will read str2 only as far as the second single quote sign (following 'That) and stop. It'll then display an error message about an "unterminated string literal" because s life!' is not set equal to anything.

Sometimes you'll have both single and double quotes in the the contents of a sentence you wish to define as a string:

He said, "That's life!"

This is where the backslash will come in handy. The backslash (\) is used to tell the compiler that the single character following it is a literal character that is not to be interpreted as code by the compiler.

var str1='He said, "That\'s life!" '; // OK!
var str2="He said, \"That's life!\" "; // OK!

Both str1 and str2 will now be read correctly by the JavaScript compiler.

Certain control characters can also be specified with the backslash:

\r = carriage return
\n = newline character
\t = tab

What You Can't Do With JavaScript

JavaScript is a client-side scripting language. This is the most exciting part about it.

Why? Because you send the script as plain text to the visitor over his/her modem to be compiled and executed on the visitor's own machine only after it is downloaded.

This is a big deal. It means that JavaScript doesn't have to wait for some more data packets to be delivered from the server over the internet and through your modem to perform its actions.

This is what differentiates it from Sun Microsystems' Java®. Java® is a server-side language. That doesn't make it bad. Just different. Many folks love Java®, and it has its rightful place in the growing group of specialized web technologies.

Java® can do many things that JavaScript can't.

Because JavaScript does everything client-side, using the visitor's own computer, folks immediately got pretty worried about security. With very good reason. There are some bad folks on the Internet.

Therefore, Netscape¨ built in a number of common sense limitations to JavaScript.

The most important of these is the prohibition of file reading/writing. You can not write files to the visitor's computer, nor can you read files on the visitor's computer, with a few very special exceptions.

Now this may be vexing from time to time, since storing data from a session would be nice. Indeed, you may say to yourself, "My, that's vexing!"

But if you look at it from the other side, you will quickly agree that you don't want other folks reading your files or writing stuff to your hard drive.

Things You Can Do with JavaScript

Despite the limitations you just read about in the foregoing section, there are many exciting things that can be done to enliven your web pages with JavaScript.

You can change images on a page without reloading, do controllable animation on screen without animated .gifs, check form input before submission, do complicated mathematical calculations, make interactive games, do site searches, display low bandwith consumption pseudo-movies, create spreadsheets, tables, graphs, etc.



© Copyright 1997, John H. Keyes john.keyes@intellink.net