BUY THIS BOOK
Add to Cart

Print Book $49.99


Add to Cart

Print+PDF $64.99

Add to Cart

PDF $39.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £35.50

What is this?

Looking to Reprint or License this content?


JavaScript: The Definitive Guide
JavaScript: The Definitive Guide, Fifth Edition By David Flanagan
August 2006
Pages: 1018

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction to JavaScript
JavaScript is an interpreted programming language with object-oriented (OO) capabilities. Syntactically, the core JavaScript language resembles C, C++, and Java, with programming constructs such as the if statement, the while loop, and the && operator. The similarity ends with this syntactic resemblance, however. JavaScript is a loosely typed language, which means that variables do not need to have a type specified. Objects in JavaScript map property names to arbitrary property values. In this way, they are more like hash tables or associative arrays (in Perl) than they are like structs (in C) or objects (in C++ or Java). The OO inheritance mechanism of JavaScript is prototype-based like that of the little-known language Self. This is quite different from inheritance in C++ and Java. Like Perl, JavaScript is an interpreted language, and it draws inspiration from Perl in a number of areas, such as its regular-expression and array-handling features.
The core JavaScript language supports numbers, strings, and Boolean values as primitive datatypes. It also includes built-in support for array, date, and regular-expression objects.
JavaScript is most commonly used in web browsers, and, in that context, the general-purpose core is extended with objects that allow scripts to interact with the user, control the web browser, and alter the document content that appears within the web browser window. This embedded version of JavaScript runs scripts embedded within HTML web pages. It is commonly called client-side JavaScript to emphasize that scripts are run by the client computer rather than the web server.
The core JavaScript language and its built-in datatypes are the subject of international standards, and compatibility across implementations is very good. Parts of client-side JavaScript are formally standardized, other parts are de facto standards, and other parts are browser-specific extensions. Cross-browser compatibility is often an important concern for client-side JavaScript programmers.
This chapter is a high-level overview of JavaScript; it provides the background information you need before embarking on a study of the language. As motivation and introduction, it includes some simple examples of client-side JavaScript code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is JavaScript?
JavaScript is the subject of a fair bit of misinformation and confusion. Before proceeding any further, it is important to debunk two common and persistent myths about the language.
One of the most common misconceptions about JavaScript is that it is a simplified version of Java, the programming language from Sun Microsystems. Other than an incomplete syntactic resemblance and the fact that both Java and JavaScript can provide executable content in web browsers, the two languages are entirely unrelated. The similarity of names is purely a marketing ploy by Netscape and Sun (the language was originally called LiveScript; its name was changed to JavaScript at the last minute). However, JavaScript can, in fact, script Java (see and 23).
Because JavaScript is interpreted instead of compiled, it is often considered a scripting language instead of a true programming language. The implication is that scripting languages are simpler and that they are programming languages for nonprogrammers. The fact that JavaScript is loosely typed does make it somewhat more forgiving for unsophisticated programmers. And many web designers have been able to use JavaScript for limited, cookbook-style programming tasks.
Beneath its thin veneer of simplicity, however, JavaScript is a full-featured programming language, as complex as any and more complex than some. Programmers who attempt to use JavaScript for nontrivial tasks often find the process frustrating if they do not have a solid understanding of the language. This book documents JavaScript comprehensively so that you can develop a sophisticated understanding. If you are used to cookbook-style JavaScript tutorials, you may be surprised at the depth and detail of the chapters ahead.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Versions of JavaScript
Like any new technology, JavaScript evolved quickly when it was new. Previous editions of this book documented this evolution version by version, explaining exactly which language features were introduced in which version of the language. At the time of this writing, however, the language has stabilized and has been standardized by the European Computer Manufacturer's Association, or ECMA. Implementations of this standard include the JavaScript 1.5 interpreter from Netscape and the Mozilla Foundation, and the JScript 5.5 interpreter from Microsoft. Any web browser newer than Netscape 4.5 or Internet Explorer 4 supports the latest version of the language. As a practical matter, you are unlikely to encounter a noncompliant interpreter.
Note that the official name of the language, according to the ECMA-262 standard, is ECMAScript. But this awkward name is normally used only when making explicit reference to the standard. Technically, the name "JavaScript" refers only to language implementations from Netscape and the Mozilla Foundation. In practice, however, everyone calls the language JavaScript.
After a long period of stability for JavaScript, there are now some signs of change. The Firefox 1.5 web browser from the Mozilla Foundation includes a new JavaScript interpreter with the version number 1.6. This version includes new (nonstandard) array manipulation methods described in , as well as support for E4X, which is described next.
In addition to the ECMA-262 specification that standardizes the core JavaScript language, ECMA has released another JavaScript-related standard. ECMA-357 standardizes an extension to JavaScript known as E4X, or ECMAScript for XML. This extension adds an XML datatype to the language along with operators and statements for manipulating XML values. At the time of this writing, E4X is implemented only by JavaScript 1.6 and Firefox 1.5. E4X is not documented formally in this book, but includes an extended introduction in tutorial form.
Proposals for a fourth edition of the ECMA-262 specification, to standardize JavaScript 2.0, have been on the table for a number of years. These proposals describe a complete overhaul of the language, including strong typing and true class-based inheritance. To date, there has been little progress toward standardization of JavaScript 2.0. Nevertheless, implementations based on draft proposals include Microsoft's JScript.NET language and the ActionScript 2.0 and ActionScript 3.0 languages used in the Adobe (formerly Macromedia) Flash player. At the time of this writing, there are signs that work on JavaScript 2.0 is resuming, and the release of JavaScript 1.6 can be seen as a preliminary step in this direction. Any new version of the language is expected to be backward-compatible with the version documented here, of course. And even once JavaScript 2.0 is standardized, it will take a few years before it is universally deployed in web browsers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Client-Side JavaScript
When a JavaScript interpreter is embedded in a web browser, the result is client-side JavaScript. This is by far the most common variant of JavaScript; when most people refer to JavaScript, they usually mean client-side JavaScript. This book documents client-side JavaScript, along with the core JavaScript language that client-side JavaScript incorporates.
Client-side JavaScript combines the scripting ability of a JavaScript interpreter with the Document Object Model (DOM) defined by a web browser. Documents may contain JavaScript scripts, and those scripts can use the DOM to modify the document or control the web browser that displays the document. Put another way, we can say that client-side JavaScript adds behavior to otherwise static web content. Client-side JavaScript is at the heart of web development techniques such as DHTML (see ) and architectures such as Ajax (see ). The introduction to includes an overview of the many capabilities of client-side JavaScript.
Just as the ECMA-262 specification defines a standard version of the core JavaScript language, the World Wide Web Consortium (W3C) has published a DOM specification that standardizes the features a browser must support in its DOM. (You'll learn much more about this standard in , 16, and 17.) The core portions of the W3C DOM standard are well supported in all major web browsers. One notable exception is Microsoft Internet Explorer, which does not support the W3C standard for event handling.
When a web browser is augmented with a JavaScript interpreter, it allows executable content to be distributed over the Internet in the form of JavaScript scripts. shows what this looks like: it is a simple JavaScript program, or script, embedded in an HTML file.
Example 1-1. A simple JavaScript program
<html>
<head><title>Factorials</title></head>
<body>
<h2>Table of Factorials</h2>
<script>
var fact = 1;
for(i = 1; i < 10; i++) {
    fact = fact*i;
    document.write(i + "! = " + fact + "<br>");
}
</script>
</body>
</html>
When loaded into a JavaScript-enabled browser, this script produces the output shown in .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JavaScript in Other Contexts
JavaScript is a general-purpose programming language, and its use is not restricted to web browsers. JavaScript was designed to be embedded within, and provide scripting capabilities for, any application. From the earliest days, in fact, Netscape's web servers included a JavaScript interpreter so that server-side scripts could be written in JavaScript. Similarly, Microsoft uses its JScript interpreter in its IIS web server and in its Windows Scripting Host product in addition to using it in Internet Explorer. Adobe uses a language derived from JavaScript for scripting its Flash player. And Sun bundles a JavaScript interpreter with its Java 6.0 distribution so that scripting capabilities can easily be added to any Java application ( shows how to do this).
Both Netscape and Microsoft have made their JavaScript interpreters available to companies and programmers who want to embed them in their applications. Netscape's interpreter was released as open source and is now available through the Mozilla organization (see http://www.mozilla.org/js/). Mozilla actually provides two different versions of the JavaScript 1.5 interpreter. One is written in C and is called SpiderMonkey. The other is written in Java and, in a flattering reference to this book, is called Rhino.
If you are writing scripts for an application that includes an embedded JavaScript interpreter, you'll find the first half of this book, documenting the core language, to be useful. The web-browser-specific chapters, however, will probably not be applicable to your scripts.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exploring JavaScript
The way to really learn a new programming language is to write programs with it. As you read through this book, I encourage you to try out JavaScript features as you learn about them. A number of techniques make it easy to experiment with JavaScript.
The most obvious way to explore JavaScript is to write simple scripts. One of the nice things about client-side JavaScript is that anyone with a web browser and a simple text editor has a complete development environment; there is no need to buy or download special-purpose software in order to begin writing JavaScript scripts.
For example, you could modify to display Fibonacci numbers instead of factorials:
<script>
document.write("<h2>Table of Fibonacci Numbers</h2>");
for (i=0, j=1, k=0, fib =0; i<50; i++, fib=j+k, j=k, k=fib){
    document.write("Fibonacci ("  + i +  ") = " + fib);
    document.write("<br>");
}
</script>
This code may be convoluted (and don't worry if you don't yet understand it), but the point is that when you want to experiment with short programs like this, you can simply type them up and try them out in your web browser using a local file: URL. Note that the code uses the document.write() method to display its HTML output so that you can see the results of its computations. This is an important technique for experimenting with JavaScript. As an alternative, you can also use the alert() method to display plain-text output in a dialog box:
alert("Fibonacci ("  + i +  ") = " + fib);
Note also that for simple JavaScript experiments like this, you can omit the <html>, <head>, and <body> tags in your HTML file.
For even simpler experiments with JavaScript, you can sometimes use the javascript: URL pseudoprotocol to evaluate a JavaScript expression and return the result. A JavaScript URL consists of the javascript: protocol specifier followed by arbitrary JavaScript code (with statements separated from one another by semicolons). When the browser loads such a URL, it executes the JavaScript code. The value of the last expression in the URL is converted to a string, and this string is displayed by the web browser as its new document. For example, you might type the following JavaScript URLs into the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Lexical Structure
The lexical structure of a programming language is the set of elementary rules that specifies how you write programs in that language. It is the lowest-level syntax of a language; it specifies such things as what variable names look like, what characters are used for comments, and how one program statement is separated from the next. This short chapter documents the lexical structure of JavaScript.
JavaScript programs are written using the Unicode character set. Unlike the 7-bit ASCII encoding, which is useful only for English, and the 8-bit ISO Latin-1 encoding, which is useful only for English and major Western European languages, the 16-bit Unicode encoding can represent virtually every written language in common use on the planet. This is an important feature for internationalization and is particularly important for programmers who do not speak English.
American and other English-speaking programmers typically write programs using a text editor that supports only the ASCII or Latin-1 character encodings, and thus they don't have easy access to the full Unicode character set. This is not a problem, however, because both the ASCII and Latin-1 encodings are subsets of Unicode, so any JavaScript program written using those character sets is perfectly valid. Programmers who are used to thinking of characters as 8-bit quantities may be disconcerted to know that JavaScript represents each character using 2 bytes, but this fact is actually transparent to the programmer and can simply be ignored.
Although the ECMAScript v3 standard allows Unicode characters anywhere in a JavaScript program, versions 1 and 2 of the standard allow Unicode characters only in comments and quoted string literals; all elements are restricted to the ASCII character set. Versions of JavaScript that predate ECMAScript standardization typically do not support Unicode at all.
JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. The
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Character Set
JavaScript programs are written using the Unicode character set. Unlike the 7-bit ASCII encoding, which is useful only for English, and the 8-bit ISO Latin-1 encoding, which is useful only for English and major Western European languages, the 16-bit Unicode encoding can represent virtually every written language in common use on the planet. This is an important feature for internationalization and is particularly important for programmers who do not speak English.
American and other English-speaking programmers typically write programs using a text editor that supports only the ASCII or Latin-1 character encodings, and thus they don't have easy access to the full Unicode character set. This is not a problem, however, because both the ASCII and Latin-1 encodings are subsets of Unicode, so any JavaScript program written using those character sets is perfectly valid. Programmers who are used to thinking of characters as 8-bit quantities may be disconcerted to know that JavaScript represents each character using 2 bytes, but this fact is actually transparent to the programmer and can simply be ignored.
Although the ECMAScript v3 standard allows Unicode characters anywhere in a JavaScript program, versions 1 and 2 of the standard allow Unicode characters only in comments and quoted string literals; all elements are restricted to the ASCII character set. Versions of JavaScript that predate ECMAScript standardization typically do not support Unicode at all.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Case Sensitivity
JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. The while keyword, for example, must be typed "while," not "While" or "WHILE." Similarly, online, Online, OnLine, and ONLINE are four distinct variable names.
Note, however, that HTML is not case-sensitive (although XHTML is). Because of its close association with client-side JavaScript, this difference can be confusing. Many JavaScript objects and properties have the same names as the HTML tags and attributes they represent. While these tags and attribute names can be typed in any case in HTML, in JavaScript they typically must be all lowercase. For example, the HTML onclick event handler attribute is sometimes specified as onClick in HTML, but it must be specified as onclick in JavaScript code (or in XHTML documents).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear between tokens in programs. Because you can use spaces, tabs, and newlines freely in your programs, you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand. Note, however, that there is one minor restriction on the placement of line breaks; it is described in the following section.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Optional Semicolons
Simple statements in JavaScript are generally followed by semicolons (;), just as they are in C, C++, and Java. The semicolon serves to separate statements from each other. In JavaScript, however, you may omit the semicolon if each of your statements is placed on a separate line. For example, the following code could be written without semicolons:
a = 3;
b = 4;
But when formatted as follows, the first semicolon is required:
a = 3; b = 4;
Omitting semicolons is not a good programming practice; you should get in the habit of using them.
Although JavaScript theoretically allows line breaks between any two tokens, the fact that JavaScript automatically inserts semicolons for you causes some exceptions to this rule. Loosely, if you break a line of code in such a way that the line before the break appears to be a complete statement, JavaScript may think you omitted the semicolon and insert one for you, altering your meaning. Some places you should look out for this are with the return, break, and continue statements (which are described in ). For example, consider the following:
return
true;
JavaScript assumes you meant:
return;
true;
However, you probably meant:
return true;
This is something to watch out for: this code does not cause a syntax error and will fail in a nonobvious way. A similar problem occurs if you write:
break
outerloop;
JavaScript inserts a semicolon after the break keyword, causing a syntax error when it tries to interpret the next line. For similar reasons, the ++ and −− postfix operators (see ) must always appear on the same line as the expressions to which they are applied.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Comments
JavaScript, like Java, supports both C++ and C-style comments. Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript. Any text between the characters /* and */ is also treated as a comment; these C-style comments may span multiple lines but may not be nested. The following lines of code are all legal JavaScript comments:
// This is a single-line comment.
/* This is also a comment */  // and here is another comment.
/*
 * This is yet another comment.
 * It has multiple lines.
 */
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Literals
A literal is a data value that appears directly in a program. The following are all literals:
12               // The number twelve
1.2              // The number one point two
"hello world"    // A string of text
'Hi'             // Another string
true             // A Boolean value
false            // The other Boolean value
/javascript/gi   // A "regular expression" literal (for pattern matching)
null             // Absence of an object
In ECMAScript v3, expressions that serve as array and object literals are also supported. For example:
{ x:1, y:2 }    // An object initializer
[1,2,3,4,5]     // An array initializer
Literals are an important part of any programming language, because it is impossible to write a program without them. The various JavaScript literals are described in detail in .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Identifiers
An identifier is simply a name. In JavaScript, identifiers are used to name variables and functions, and to provide labels for certain loops in JavaScript code. The rules for legal identifier names are the same in JavaScript as they are in Java and many other languages. The first character must be a letter, an underscore (_), or a dollar sign ($). Subsequent characters can be a letter, a digit, an underscore, or a dollar sign. (Digits are not allowed as the first character so that JavaScript can easily distinguish identifiers from numbers.) These are all legal identifiers:
i
my_variable_name
v13
_dummy
$str
In ECMAScript v3, identifiers can contain letters and digits from the complete Unicode character set. Prior to this version of the standard, JavaScript identifiers were restricted to the ASCII character set. ECMAScript v3 also allows Unicode escape sequences to appear in identifiers. A Unicode escape contains the characters \u followed by four hexadecimal digits that specify a 16-bit character encoding. For example, the identifier π can also be written as \u03c0. Although this is an awkward syntax, it makes it possible to translate JavaScript programs that contain Unicode characters into a form that allows them to be manipulated with text editors and other tools that do not support the full Unicode character set.
Finally, identifiers can't be the same as any of the keywords used for other purposes in JavaScript. The next section lists the special keywords that are reserved in JavaScript.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Reserved Words
JavaScript has a number of reserved keywords. These are words that you cannot use as identifiers (variable names, function names, and loop labels) in your JavaScript programs. lists the keywords standardized by ECMAScript v3. These words have special meaning to JavaScript; they are part of the language syntax itself.
Table 2-1: Reserved JavaScript keywords
break
do
if
switch
typeof
case
else
in
this
var
catch
false
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Datatypes and Values
Computer programs work by manipulating values, such as the number 3.14 or the text "Hello World." The types of values that can be represented and manipulated in a programming language are known as datatypes, and one of the most fundamental characteristics of a programming language is the set of datatypes it supports. JavaScript allows you to work with three primitive datatypes: numbers, strings of text (known as strings), and Boolean truth values (known as booleans). JavaScript also defines two trivial datatypes, null and undefined, each of which defines only a single value.
In addition to these primitive datatypes, JavaScript supports a composite datatype known as an object. An object (that is, a member of the datatype object) represents a collection of values (either primitive values, such as numbers and strings, or composite values, such as other objects). Objects in JavaScript have a dual nature: an object can represent an unordered collection of named values or an ordered collection of numbered values. In the latter case, the object is called an array. Although objects and arrays are fundamentally the same datatype in JavaScript, they behave quite differently and will usually be considered distinct types throughout this book.
JavaScript defines another special kind of object, known as a function. A function is an object that has executable code associated with it. A function may be invoked to perform some kind of operation. Like arrays, functions behave differently from other kinds of objects, and JavaScript defines a special language syntax for working with them. Thus, we'll treat the function datatype independently of the object and array types.
In addition to functions and arrays, core JavaScript defines a few other specialized kinds of objects. These objects do not represent new datatypes, just new classes of objects. The Date class defines objects that represent dates, the RegExp class defines objects that represent regular expressions (a powerful pattern-matching tool described in ), and the Error class defines objects that represent syntax and runtime errors that can occur in a JavaScript program.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Numbers
Numbers are the most basic datatype; they require very little explanation. JavaScript differs from programming languages such as C and Java in that it does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard, which means it can represent numbers as large as ±1.7976931348623157 × 10308 and as small as ±5 × 10−324.
When a number appears directly in a JavaScript program, it's called a numeric literal. JavaScript supports numeric literals in several formats, as described in the following sections. Note that any numeric literal can be preceded by a minus sign (-) to make the number negative. Technically, however, - is the unary negation operator (see ) and is not part of the numeric literal syntax.
In a JavaScript program, a base-10 integer is written as a sequence of digits. For example:
0
3
10000000
The JavaScript number format allows you to exactly represent all integers between −9007199254740992 (−253) and 9007199254740992 (253), inclusive. If you use integer values larger than this, you may lose precision in the trailing digits. Note, however, that certain integer operations in JavaScript (in particular the bitwise operators described in ) are performed on 32-bit integers, which range from −2147483648 (−231 ) to 2147483647 (231−1).
In addition to base-10 integer literals, JavaScript recognizes hexadecimal (base-16) values. A hexadecimal literal begins with "0x" or "0X", followed by a string of hexadecimal digits. A hexadecimal digit is one of the digits 0 through 9 or the letters a (or A) through f (or F), which represent values 10 through 15. Here are examples of hexadecimal integer literals:
0xff  // 15*16 + 15 = 255 (base 10)
0xCAFE911
Although the ECMAScript standard does not support them, some implementations of JavaScript allow you to specify integer literals in octal (base-8) format. An octal literal begins with the digit 0 and is followed by a sequence of digits, each between 0 and 7. For example:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Strings
A string is a sequence of Unicode letters, digits, punctuation characters, and so on; it is the JavaScript datatype for representing text. As you'll see shortly, you can include string literals in your programs by enclosing them in matching pairs of single or double quotation marks. Note that JavaScript does not have a character datatype such as char, as C, C++, and Java do. To represent a single character, you simply use a string that has a length of 1.
A string comprises a sequence of zero or more Unicode characters enclosed within single or double quotes (' or "). Double-quote characters may be contained within strings delimited by single-quote characters, and single-quote characters may be contained within strings delimited by double quotes. String literals must be written on a single line; they may not be broken across two lines. If you need to include a newline character in a string literal, use the character sequence \n, which is documented in the next section. Here are examples of string literals:
""  // The empty string: it has zero characters
'testing'
"3.14"
'name="myform"'
"Wouldn't you prefer O'Reilly's book?"
"This string\nhas two lines"
"π is the ratio of a circle's circumference to its diameter"
As illustrated in the last example string shown, the ECMAScript v1 standard allows Unicode characters within string literals. Implementations prior to JavaScript 1.3, however, typically support only ASCII or Latin-1 characters in strings. As explained in the next section, you can also include Unicode characters in your string literals using special escape sequences. This is useful if your text editor does not provide complete Unicode support.
Note that when you use single quotes to delimit your strings, you must be careful with English contractions and possessives, such as can't and O'Reilly's. Since the apostrophe is the same as the single-quote character, you must use the backslash character (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Boolean Values
The number and string datatypes have a large or infinite number of possible values. The boolean datatype, on the other hand, has only two. These two values are represented by the literals true and false. A value of type boolean represents a truth value; it says whether something is true or not.
Boolean values are generally the result of comparisons you make in your JavaScript programs. For example:
a == 4
This code tests to see whether the value of the variable a is equal to the number 4. If it is, the result of this comparison is the boolean value true. If a is not equal to 4, the result of the comparison is false.
Boolean values are typically used in JavaScript control structures. For example, the if/else statement in JavaScript performs one action if a boolean value is true and another action if the value is false. You usually combine a comparison that creates a boolean value directly with a statement that uses it. The result looks like this:
if (a == 4)
  b = b + 1;
else
  a = a + 1;
This code checks whether a equals 4. If so, it adds 1 to b; otherwise, it adds 1 to a.
Instead of thinking of the two possible boolean values as true and false, it is sometimes convenient to think of them as on (true) and off (false), or yes (true) and no (false).
Boolean values are easily convertible to and from other types and are often automatically converted. If a boolean value is used in a numeric context, true converts to the number 1 and false converts to the number 0. If a boolean value is used in a string context, true converts to the string "true" and false converts to the string "false".
If a number is used where a boolean value is expected, the number is converted to true unless the number is 0 or NaN, which are converted to false. If a string is used where a boolean value is expected, it is converted to true except for the empty string, which is converted to false. null and the undefined value convert to false, and any non-null object, array, or function converts to true.
If you prefer to make your type conversions explicit, you can use the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions
A function is a piece of executable code that is defined by a JavaScript program or predefined by the JavaScript implementation. Although a function is defined only once, a JavaScript program can execute or invoke it any number of times. A function may be passed arguments, or parameters, specifying the value or values upon which it is to perform its computation, and it may also return a value that represents the results of that computation. JavaScript implementations provide many predefined functions, such as the Math.sin( ) function that computes the sine of an angle.
JavaScript programs may also define their own functions with code that looks like this:
function square(x) // The function is named square. It expects one argument, x.
{                  // The body of the function begins here.
  return x*x;      // The function squares its argument and returns that value.
}                  // The function ends here.
Once a function is defined, you can invoke it by following the function's name with an optional comma-separated list of arguments within parentheses. The following lines are function invocations:
y = Math.sin(x);
y = square(x);
d = compute_distance(x1, y1, z1, x2, y2, z2);
move( );
An important feature of JavaScript is that functions are values that can be manipulated by JavaScript code. In many languages, including Java, functions are only a syntactic feature of the language: they can be defined and invoked, but they are not datatypes. The fact that functions are true values in JavaScript gives a lot of flexibility to the language. It means that functions can be stored in variables, arrays, and objects, and it means that functions can be passed as arguments to other functions. This can quite often be useful. Defining and invoking functions, as well as how to use them as data values, are discussed in .
Since functions are values just like numbers and strings, they can be assigned to object properties just as other values can. When a function is assigned to a property of an object (the object datatype and object properties are described in ), it is often referred to as a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Objects
An object is a collection of named values. These named values are usually referred to as properties of the object. (Sometimes they are called fields of the object, but this usage can be confusing.) To refer to a property of an object, you refer to the object, followed by a period and the name of the property. For example, if an object named image has properties named width and height, you can refer to those properties like this:
image.width
image.height
Properties of objects are, in many ways, just like JavaScript variables; they can contain any type of data, including arrays, functions, and other objects. Thus, you might see JavaScript code like this:
document.myform.button
This code refers to the button property of an object that is itself stored in the myform property of an object named document.
As mentioned earlier, when a function value is stored in a property of an object, that function is often called a method, and the property name becomes the method name. To invoke a method of an object, use the . syntax to extract the function value from the object and then use the ( ) syntax to invoke that function. For example, to invoke the write( ) method of an object named document, you can use code like this:
document.write("this is a test");
Objects in JavaScript can serve as associative arrays; that is, they can associate arbitrary data values with arbitrary strings. When an object is used in this way, a different syntax is generally required to access the object's properties: a string containing the name of the desired property is enclosed within square brackets. Using this syntax, you can access the properties of the image object mentioned previously with code like this:
image["width"]
image["height"]
Associative arrays are a powerful datatype; they are useful for a number of programming techniques. I describe objects in their traditional and associative array usages in .
As you'll see in , objects are created by invoking special constructor functions. For example, the following lines all create new objects:
var o = new Object( );
var now = new Date( );
var pattern = new RegExp("\\sjava\\s", "i");
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Arrays
An array is a collection of data values, just as an object is. While each data value contained in an object has a name, each data value in an array has a number, or index. In JavaScript, you retrieve a value from an array by enclosing an index in square brackets after the array name. For example, if an array is named a and i is a nonnegative integer, a[i] is an element of the array. Array indexes begin with zero; thus, a[2] refers to the third element of the array a.
Arrays may contain any type of JavaScript data, including references to other arrays or to objects or functions. For example:
document.images[1].width
This code refers to the width property of an object stored in the second element of an array stored in the images property of the document object.
Note that the arrays described here differ from the associative arrays described in . The regular arrays we are discussing here are indexed by nonnegative integers. Associative arrays are indexed by strings. Also note that JavaScript does not support multidimensional arrays, except as arrays of arrays. Finally, because JavaScript is an untyped language, the elements of an array do not all need to be of the same type, as they do in typed languages like Java. Arrays are discussed further in .
Arrays can be created with the Array( ) constructor function. Once created, any number of indexed elements can easily be assigned to the array:
var a = new Array( );
a[0] = 1.2;
a[1] = "JavaScript";
a[2] = true;
a[3] = { x:1, y:3 };
Arrays can also be initialized by passing array elements to the Array( ) constructor. Thus, the previous array creation and initialization code can also be written:
var a = new Array(1.2, "JavaScript", true, { x:1, y:3 });
If you pass only a single number to the Array( ) constructor, it specifies the length of the array. Thus:
var a = new Array(10);
creates a new array with 10 undefined elements.
JavaScript defines a literal syntax for creating and initializing arrays. An array literal (or array initializer) is a comma-separated list of values contained within square brackets. The values within the brackets are assigned sequentially to array indexes starting with zero. For example, the array creation and initialization code in the previous section can also be written as:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
null
The JavaScript keyword null is a special value that indicates no value. null is usually considered a special value of object type—a value that represents no object. null is a unique value, distinct from all other values. When a variable holds the value null, you know that it does not contain a valid object, array, number, string, or boolean value.
When null is used in a Boolean context, it converts to false. When used in a numeric context, it converts to 0. And when used in a string context, it converts to "null".
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
undefined
Another special value used occasionally by JavaScript is the undefined value. undefined is returned when you use either a variable that has been declared but never had a value assigned to it or an object property that does not exist. Note that this special undefined value is not the same as null.
Although null and the undefined value are distinct, the == equality operator considers them equal to one another. Consider the following:
my.prop == null
This comparison is true if either the my.prop property does not exist or it does exist but contains the value null. Since both null and the undefined value indicate an absence of value, this equality is often what we want. However, if you truly must distinguish between a null value and an undefined value, use the === identity operator or the typeof operator (see for details).
Unlike null, undefined is not a reserved word in JavaScript. The ECMAScript v3 standard specifies that there is always a global variable named undefined whose initial value is the undefined value. Thus, in a conforming implementation, you can treat undefined as a keyword, as long as you don't assign a value to the variable.
If you are not sure that your implementation has the undefined variable, you can simply declare your own:
var undefined;
By declaring but not initializing the variable, you assure your implementation has the undefined value. The void operator (see ) provides another way to obtain the undefined value.
When the undefined value is used in a Boolean context, it converts to false. When used in a numeric context, it converts to NaN. And when used in a string context, it converts to "undefined".
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Date Object
The previous sections have described all the fundamental datatypes supported by JavaScript. Date and time values are not one of these fundamental types, but JavaScript does provide a class of object that represents dates and times and can be used to manipulate this type of data. A Date object in JavaScript is created with the new operator and the Date( ) constructor (the new operator is introduced in , and you'll learn more about object creation in ):
var now = new Date( );  // Create an object holding the current date and time.
// Create a Date object representing Christmas.
// Note that months are zero-based, so December is month 11!
var xmas = new Date(2006, 11, 25);
Methods of the Date object allow you to get and set the various date and time values and to convert the Date to a string, using either local time or GMT time. For example:
xmas.setFullYear(xmas.getFullYear( ) + 1); // Change the date to next Christmas.
var weekday = xmas.getDay( );              // It falls on a Tuesday in 2007.
document.write("Today is: " + now.toLocaleString( ));  // Current date/time.
The Date object also defines functions (not methods; they are not invoked through a Date object) to convert a date specified in string or numeric form to an internal millisecond representation that is useful for some kinds of date arithmetic.
You can find full documentation on the Date object and its methods in .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Regular Expressions
Regular expressions provide a rich and powerful syntax for describing textual patterns; they are used for pattern matching and for implementing search and replace operations. JavaScript has adopted the Perl programming language syntax for expressing regular expressions.
Regular expressions are represented in JavaScript by the RegExp object and may be created using the RegExp( ) constructor. Like the Date object, the RegExp object is not one of the fundamental datatypes of JavaScript; it is simply a specialized kind of object provided by all conforming JavaScript implementations.
Unlike the Date object, however, RegExp objects have a literal syntax and can be encoded directly into JavaScript programs. Text between a pair of slashes constitutes a regular expression literal. The second slash in the pair can also be followed by one or more letters, which modify the meaning of the pattern. For example:
/^HTML/
/[1-9][0-9]*/
/\bjavascript\b/i
The regular-expression grammar is complex and is documented in detail in . At this point, you need only know what a regular expression literal looks like in JavaScript code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Error Objects
ECMAScript v3 defines a number of classes that represent errors. The JavaScript interpreter "throws" an object of one of these types whe