Chapter 8: Javascript
You have seen some examples of Javascript earlier in this chapter, but now
you need to learn a bit more so you can use Javascript effectively in your
Web pages. I cannot cover Javascript in its entirety--that would require its
own book--but I can show you enough to get started.
Syntax
This section covers some of the basic syntax rules of Javascript.
Javascript is Not Java
You may have heard of the popular programming language called Java. Is
Javascript related to Java? Only remotely. Java is a full-featured object-
oriented language for writing desktop and server applications, where as
Javascript is a scripting language designed for Web use. There are some
syntactical similarities between the two languages but that's about all.
Case-Sensitivity
The first thing you should know about Javascript is that it is a case-
sensitive language. Thus, the terms
COUNT,
Count, and
count will be
considered three distinct and totally independent terms in Javascript. I
know this can be really annoying, but there's no getting around it so you'll
just have to get used to it. In my experience, the best approach is to
develop a consistent approach to capitalization and stick with it.
Javascript's case-sensitivity can be even more confusing because
HTML is
not case-sensitive.
<IMG> and
<img> are the same tag, and the same is
true of attribute names.
White Space
Javascript is similar to
HTML in that it ignores most white space (spaces,
tabs, and new lines). If, for example, you have a long line of Javascript
code you can break it up over 2 or more lines. The only place that white
space is not ignored is within literal strings--text that is enclosed in double
or single quotation marks.
Semicolons
Some of the programming languages that Javascript is related to use a
semicolon to mark the end of each program statement. Javascript relaxes
this rule--you can end a statement with a semicolon but do not have to as
long as each statement is placed on a separate line. If you want to put
more than one statement on a line, semicolons are required. For example,
this is legal:
a = 1;
b = 2;
So is this:
a = 1
b = 2
And this is legal too:
a = 1; b = 2;
But this is not legal:
a = 1 b = 2;
Comments
Just like
HTML, Javascript lets you enter comments in your code. The
syntax is different, however. You can enter single line comments using a
pair of slashes. Anything following // on a line is a comment, for example:
// This is a comment.
a = 1; //This is another comment.
You can also create comments using the /* and */ character pairs.
Anything following /* up to the next */ is a comment; it can span as many
lines as you like (this is the preferred method of commenting code in
JavaScript):
/* This is
all one large
multi-line
comment. */
The only time that //, /*, and */ do not mark comments is when they are
within a quoted string.
Literals
A literal is nothing more than a data value typed directly into the program
code. They fall into three general categories:
- Numbers are typed in normally, such as 123 or 0.045. You do not
use thousands separators, such as the comma in 23,000.
- Strings, or text, are entered enclosed in single or double quotes.
Some examples are "John's Salary" and 'Mississippi'. If a string
contains a double quote it must be enclosed in single quotes and
vice versa. Otherwise it does not matter which you use.
- The special keywords true and false representing the
corresponding Boolean values, and null representing "no data or
object."
Identifiers
An identifier is a name used in a Javascript program to identify something,
typically either a variable or a function. The rules for creating identifiers
are simple:
- The first character must be a letter, an underscore (_), or a dollar
sign ($).
- Subsequent characters can be any letter, any digit, an underscore,
or a dollar sign.
The following are all legal Javascript identifiers:
count
$name
index_12
x
fred_flintstone
These are not legal:
percent%
12days
john-adams
Also, you cannot use a Javascript reserved keyword as an identifier. These
reserved words are listed in Table 8-1.
Table 8-1. Javascript reserved keywords.
break
case
catch
continue
default
delete
do
else
false
|
finally
for
function
if
in
instanceof
new
null
return
switch
|
this
throw
true
try
typeof
var
void
while
with
|
Be Descriptive
When creating identifiers for variable and function names, it is a good
idea to use names that are descriptive of the data the variable holds or the
task that the function performs.
Variables
A variable is a location to store data in a script. As the name suggests the
data in a variable can change--unlike a literal it is not set at one fixed
value. When you create a variable you give it a name; you then use that
name to refer to it in your code. To create a variable--called declaring a
variable--use the var keyword:
var variablename
Variablename is any legal Javascript identifier as described earlier in this
chapter. It must be unique within the program or, if it is declared in a
function, within that function. You can declare variables one at a time like
this:
var count;
var total;
Or, you can declare more than one in a single var statement:
var count, total;
You can initialize (assign a value to) a variable at the same time you declare it:
var name = "Arthur";
If you declare a variable without initializing it, the variable's value will be
undefined until the program stores a value in the variable. You cannot
count on an uninitialized variable having a specific value such as 0.
What happens if you try to use a variable that has not been declared?
It depends:
- If your code tries to read the value of the variable an error occurs.
- If your code sets the value of the variable, Javascript automatically
declares it.
You should not rely on the second point--it is advisable to explicitly
declare all variables. One reason for this is that automatically declared
variables always have global scope, which can cause problems. You'll learn
more about this in the section on variable scope later in the chapter.
Arrays
An array is a type of variable that can store multiple data items under the
same name, distinguishing them by a numerical index. For example, you
could create an array named months that has 12 elements, on for each
month. Then array element 1 could be used for January, element 2 for
February, and so on. To create an array you use the Array() function. One
option is to specify the number of elements the array has. This declaration
creates an array with 10 elements.
var myArray = new Array(10);
You can also specify the data in the array when you declare it:
var myArray = new Array(2, 4, 6, 8, 10);
Javascript assigns the data to the array starting with the first element, and
automatically sizes the array as needed (5 elements in this example).
Finally, you can use an array literal to create an array without using the
Array() function. Here's an example that has the same result as the
previous example:
var myArray = [2, 4, 6, 8, 10];
Javascript Arrays are Zero-based
As with most programming languages, arrays in Javascript are zero-based.
This means that the first element in the array has index 0, not 1. It also
means that the last element in the array has an index equal to one less than
the number of elements in the array. For example, a ten element array has
elements with indexes 0 through 9. A common newbie error is to try to
access that non-existent tenth element at index 10.
To access an array element you use the array name followed by the
element number in square brackets:
myArray[4] = "Happy Programming!";
document.write(myArray[4]);
You can also specify the index with a variable:
myArray[idx] = "Happy Programming!";
document.write(myArray[idx]);
If the variable
idx has the value 4, these two sections of code are
equivalent.
Javascript has the handy feature that you can change the size of an array
at any time. You can both increase and decrease an array's size. To add
elements to an array, all you need do is assign a value to one or more new
elements as shown here. Look at this variable declaration:
var myArray = new Array("red", "yellow", "blue");
This creates an array with three elements with indexes 0, 1, and 2. Then
suppose your program executes the following code:
myArray[3] = "green";
myArray[4] = "orange";
Javascript will automatically increase the array to five elements, adding
the two new elements with indexes 3 and 4.
You can also change an array's size, increasing or decreasing it, by setting
its
length property.:
myArray.length = value
If value is greater than the current array size, new elements are added as
needed. If value is smaller than the current array size, elements are
removed from the end of the array.
Determining Array Length
You can use the length property to determine the length of an array. This
can be very useful when you need to read out all the elements in an array
but do not know how many there are. I'll show you an example of this
later in the section on for loops.