BUY THIS BOOK
Add to Cart

Print Book $9.95


Add to Cart

Print+PDF $12.93

Add to Cart

PDF $7.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £6.95

What is this?

Looking to Reprint or License this content?


JavaScript Pocket Reference
JavaScript Pocket Reference, Second Edition By David Flanagan
October 2002
Pages: 136

Cover | Table of Contents


Table of Contents

Chapter 1: The JavaScript Language
JavaScript is a lightweight, object-based scripting language that can be embedded in HTML pages. This book starts with coverage of the core JavaScript language, followed by material on client-side JavaScript, as used in web browsers. The final portion of this book is a quick-reference for the core and client-side JavaScript APIs.
JavaScript syntax is modeled on Java syntax, Java syntax, in turn, is modeled on C and C++ syntax. Therefore, C, C++, and Java programmers should find that JavaScript syntax is comfortably familiar.
JavaScript is a case-sensitive language. All keywords are in lowercase. All variables, function names, and other identifiers must be typed with a consistent capitalization.
JavaScript ignores whitespace between tokens. You may use spaces, tabs, and newlines to format and indent your code in a readable fashion.
JavaScript statements are terminated by semicolons. When a statement is followed by a newline, however, the terminating semicolon may be omitted. Note that this places a restriction on where you may legally break lines in your JavaScript programs: you may not break a statement across two lines if the first line can be a complete legal statement on its own.
JavaScript supports both C and C++ comments. Any amount of text, on one or more lines, between /* and */ is a comment, and is ignored by JavaScript. Also, any text between // and the end of the current line is a comment, and is ignored. Examples:
// This is a single-line, C++-style comment.
/*
 * This is a multi-line, C-style comment.
 * Here is the second line.
 */
/* Another comment. */ // This too.
Variable, function, and label names are JavaScript identifiers. Identifiers are composed of any number of letters and digits, and _ and $ characters. The first character of an identifier must not be a digit, however. The following are legal identifiers:
i
my_variable_name
v13
$str
The following keywords are part of the JavaScript language, and have special meaning to the JavaScript interpreter. Therefore, they may not be used as identifiers:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Syntax
JavaScript syntax is modeled on Java syntax, Java syntax, in turn, is modeled on C and C++ syntax. Therefore, C, C++, and Java programmers should find that JavaScript syntax is comfortably familiar.
JavaScript is a case-sensitive language. All keywords are in lowercase. All variables, function names, and other identifiers must be typed with a consistent capitalization.
JavaScript ignores whitespace between tokens. You may use spaces, tabs, and newlines to format and indent your code in a readable fashion.
JavaScript statements are terminated by semicolons. When a statement is followed by a newline, however, the terminating semicolon may be omitted. Note that this places a restriction on where you may legally break lines in your JavaScript programs: you may not break a statement across two lines if the first line can be a complete legal statement on its own.
JavaScript supports both C and C++ comments. Any amount of text, on one or more lines, between /* and */ is a comment, and is ignored by JavaScript. Also, any text between // and the end of the current line is a comment, and is ignored. Examples:
// This is a single-line, C++-style comment.
/*
 * This is a multi-line, C-style comment.
 * Here is the second line.
 */
/* Another comment. */ // This too.
Variable, function, and label names are JavaScript identifiers. Identifiers are composed of any number of letters and digits, and _ and $ characters. The first character of an identifier must not be a digit, however. The following are legal identifiers:
i
my_variable_name
v13
$str
The following keywords are part of the JavaScript language, and have special meaning to the JavaScript interpreter. Therefore, they may not be used as identifiers:
break     do        if         switch  typeof        
case      else      in         this    var   
catch     false     instanceof throw   void  
continue  finally   new        true    while 
default   for       null       try     with
delete    function  return
JavaScript also reserves the following words for possible future extensions. You may not use any of these words as identifiers either:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
Variables are declared and initialized with the var statement:
var i = 1+2+3;
var x = 3, message = 'hello world';
Variable declarations in top-level JavaScript code may be omitted, but they are required to declare local variables within the body of a function.
JavaScript variables are untyped: they can contain values of any data type.
Global variables in JavaScript are implemented as properties of a special Global object. Local variables within functions are implemented as properties of the Argument object for that function. Global variables are visible throughout a JavaScript program. Variables declared within a function are only visible within that function. Unlike C, C++, and Java, JavaScript does not have block-level scope: variables declared within the curly braces of a compound statement are not restricted to that block and are visible outside of it.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Types
JavaScript supports three primitive data types: numbers, booleans, and strings; and two compound data types: objects and arrays. In addition, it defines specialized types of objects that represent functions, regular expressions, and dates.
Numbers in JavaScript are represented in 64-bit floating-point format. JavaScript makes no distinction between integers and floating-point numbers. Numeric literals appear in JavaScript programs using the usual syntax: a sequence of digits, with an optional decimal point and an optional exponent. For example:
1
3.14
0001
6.02e23
Integers may also appear in hexadecimal notation. A hexadecimal literal begins with 0x:
0xFF // The number 255 in hexadecimal
When a numeric operation overflows, it returns a special value that represents positive or negative infinity. When an operation underflows, it returns zero. When an operation such as taking the square root of a negative number yields an error or meaningless result, it returns the special value NaN, which represents a value that is not-a-number. Use the global function isNaN( ) to test for this value.
The Number object defines useful numeric constants. The Math object defines various mathematical functions such as Math.sin( ), Math.pow( ), and Math.random( ).
The boolean type has two possible values, represented by the JavaScript keywords true and false. These values represent truth or falsehood, on or off, yes or no, or anything else that can be represented with one bit of information.
A JavaScript string is a sequence of arbitrary letters, digits, and other characters from the 16-bit Unicode character set.
String literals appear in JavaScript programs between single or double quotes. One style of quotes may be nested within the other:
'testing'
"3.14"
'name="myform"'
"Wouldn't you prefer O'Reilly's book?"
When the backslash character (\) appears within a string literal, it changes, or escapes, the meaning of the character that follows it. The following table lists these special escape sequences:
Escape
Represents
\b
Backspace
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expressions and Operators
JavaScript expressions are formed by combining values (which may be literals, variables, object properties, array elements, or function invocations) using JavaScript operators. Parentheses can be used in an expression to group subexpressions and alter the default order of evaluation of the expression. Some examples:
1+2
total/n
sum(o.x, a[3])++
JavaScript defines a complete set of operators, most of which should be familiar to C, C++, and Java programmers. They are listed in the table below, and a brief explanation of the non-standard operators follows. The P column specifies operator precedence and the A column specifies operator associativity: L means left-to-right associativity, and R means right-to-left associativity.
P
A
Operator
Operation performed
15
L
.
Access an object property
L
[ ]
Access an array element
L
( )
Invoke a function
R
new
Create new object
14
R
++
Pre-or-post increment (unary)
R
--
Pre-or-post decrement (unary)
R
-
Unary minus (negation)
R
+
Unary plus (no-op)
R
~
Bitwise complement (unary)
R
!
Logical complement (unary)
R
delete
Undefine a property (unary) (JS 1.2)
R
typeof
Return data type (unary) (JS 1.1)
R
void
Return undefined value (unary) (JS 1.1)
13
L
*, /, %
Multiplication, division, remainder
12
L
+, -
Add, subtract
L
+
Concatenate strings
11
L
<<
Integer shift left
L
>>
Shift right, sign-extension
L
>>>
Shift right, zero extension
10
L
<, <=
Less than, less than or equal
L
>, >=
Greater than, greater than or equal
L
instanceof
Check object type (JS 1.5)
L
in
Check whether property exists (JS 1.5)
9
L
==
Test for equality
L
!=
Test for inequality
L
===
Test for identity (JS 1.3)
L
!==
Test for non-identity (JS 1.3)
8
L
&
Integer bitwise AND
7
L
^
Integer bitwise XOR
6
L
|
Integer bitwise OR
5
L
&&
Logical AND
4
L
||
Logical OR
3
R
?:
Conditional operator (3 operands)
2
R
=
Assignment
R
*=, +=, -=, etc.
Assignment with operation
1
L
,
Multiple evaluation
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Statements
A JavaScript program is a sequence of JavaScript statements. Most JavaScript statements have the same syntax as the corresponding C, C++, and Java statements.
Every JavaScript expression can stand alone as a statement. Assignments, method calls, increments, and decrements are expression statements. For example:
s = "hello world";
x = Math.sqrt(4);
x++;
When a sequence of JavaScript statements is enclosed within curly braces, it counts as a single compound statement. For example, the body of a while loop consists of a single statement. If you want the loop to execute more than one statement, use a compound statement. This is a common technique with if, for, and other statements described later.
The empty statement is simply a semicolon by itself. It does nothing, and is occasionally useful for coding empty loop bodies.
As of JavaScript 1.2, any statement can be labeled with a name. Labeled loops can then be used with the labeled versions of the break and continue statements:
label : statement
The following paragraphs document all JavaScript statements, in alphabetical order.
break
The break statement terminates execution of the innermost enclosing loop, or, in JavaScript 1.2 and later, the named loop:
break ;
break label ;
case
case is not a true statement. Instead it is a keyword used to label statements within a JavaScript 1.2 or later switch statement:
case constant-expression :
    statements
    [ break ; ]
Because of the nature of the switch statement, a group of statements labeled by case should usually end with a break statement.
continue
The continue statement restarts the innermost enclosing loop, or, in JavaScript 1.2 and later, restarts the named loop:
continue ;
continue label ;
default
Like case, default is not a true statement, but instead a label that may appear within a JavaScript 1.2 or later switch statement:
default:
    statements
    [ break ; ]
do/while
The do/while loop repeatedly executes a statement while an expression is true. It is like the while loop, except that the loop condition appears (and is tested) at the bottom of the loop. This means that the body of the loop is executed at least once:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object-Oriented JavaScript
JavaScript objects are associative arrays that associate values with named properties. JavaScript provides a simple inheritance mechanism, and it is possible to define new classes of objects for use in your own programs. To define a new class, start by writing a constructor function. A constructor is like any other function, except it is invoked with the new operator and it uses the this keyword to refer to and initialize the newly created object. For example, here is a constructor to create objects of a new class named Point.
function Point(x,y) { // Constructor for Point
  this.x = x;  // Initialize X coordinate
  this.y = y;  // Initialize Y coordinate
}
Every JavaScript function used as a constructor has a property named prototype. This property refers to a special prototype object for the class of objects created by the constructor. Any properties you define on this prototype object are inherited by all objects created with the constructor function. The prototype object is commonly used to make methods available to all instances of a class. Defining a method named toString allows instances of your class to be converted to strings. For example:
// Define function literals and assign them 
// to properties of the prototype object.
Point.prototype.distanceTo = function(that) {
  var dx = this.x - that.x;
  var dy = this.y - that.y;
  return Math.sqrt(dx*dx + dy*dy);
}
Point.prototype.toString = function () {
  return '(' + this.x + ',' + this.y + ')';
}
If you want to define static (or class) methods or properties, you can assign them directly to the constructor function, rather than to the prototype object. For example:
// Define a commonly used Point constant
Point.ORIGIN = new Point(0,0);
The preceding code fragments define a simple Point class that we can use with code like this:
// Call constructor to create a new Point object
var p = new Point(3,4);
// Invoke a method of the object, using a static
// property as the argument.  
var d = p.distanceTo(Point.ORIGIN);
// Adding the object to a string implicitly
// invokes toString().
var msg = "Distance to " + p + " is " + d;
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
JavaScript supports regular expressions for pattern matching with the same syntax as the Perl programming language. JavaScript 1.2 supports Perl 4 regular expressions, and JavaScript 1.5 adds supports for some of the additional features of Perl 5 regular expressions. A regular expression is specified literally in a JavaScript program as a sequence of characters within slash (/) characters, optionally followed by one or more of the modifier characters g (global search), i (case-insensitive search), and m (multi-line mode; a JavaScript 1.5 feature). In addition to this literal syntax, RegExp objects can be created with the RegExp( ) constructor, which accepts the pattern and modifier characters as string arguments, without the slash characters.
A full explanation of regular expression syntax is beyond the scope of this book, but the tables in the following subsections offer brief syntax summaries.
Letters, numbers, and most other characters are literals in a regular expression: they simply match themselves. As we'll see in the sections that follow, however, there are a number of punctuation characters and escape sequences (beginning with \) that have special meanings. The simplest of these escape sequences provide alternative ways of representing literal characters:
Character
Meaning
\n, \r, \t
Match literal newline, carriage return, tab
\\, \/, \*,\+, \?, etc.
Match a punctuation character literally, ignoring or escaping its special meaning
\xnn
The character with hexadecimal encoding nn.
\uxxxx
The Unicode character with hexadecimal encoding xxxx.
Regular expression syntax uses square brackets to represent character sets or classes in a pattern. In addition, escape sequences define certain commonly-used character classes, as shown in the following table.
Character
Meaning
[...]
Match any one character between brackets
[^...]
Match any one character not between brackets
.
Match any character other than newline
\w, \W
Match any word/non-word character
\s, \S
Match any whitespace/non-whitespace
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
Netscape has defined a number of versions of JavaScript. Microsoft has released more-or-less compatible versions under the name "JScript," and the ECMA standards body has released three versions of a JavaScript standard named "ECMAScript". The following paragraphs describe these various versions, and explain how they relate to each other. Each entry in the reference section contains availability information that documents the version of JavaScript in which a feature was introduced.
JavaScript 1.0
The original version of the language. It was buggy and is now essentially obsolete. Implemented by Netscape 2.
JavaScript 1.1
Introduced a true Array object; most serious bugs resolved. Implemented by Netscape 3.
JavaScript 1.2
Introduced the switch statement, regular expressions, and a number of other features. Almost compliant with ECMA v1, but has some incompatibilities. Implemented by Netscape 4.
JavaScript 1.3
Fixed incompatibilities of JavaScript 1.2. Compliant with ECMA v1. Implemented by Netscape 4.5.
JavaScript 1.4
Only implemented in Netscape server products.
JavaScript 1.5
Introduced exception handling. Compliant with ECMA v3. Implemented by Mozilla and Netscape 6.
JScript 1.0
Roughly equivalent to JavaScript 1.0. Implemented by early releases of IE 3.
JScript 2.0
Roughly equivalent to JavaScript 1.1. Implemented by later releases of IE 3.
JScript 3.0
Roughly equivalent to JavaScript 1.3. Compliant with ECMA v1. Implemented by IE 4.
JScript 4.0
Not implemented by any web browser.
JScript 5.0
Supported exception handling; partial ECMA v3 compliance. Implemented by IE 5.
JScript 5.5
Roughly equivalent to JavaScript 1.5. Fully compliant with ECMA v3. Implemented by IE 5.5 and IE 6.
ECMA v1
The first standard version of the language. Standardized the basic features of JavaScript 1.1 and added a few new features. Did not standardize the switch statement or regular expression support. Conformant implementations are JavaScript 1.3 and JScript 3.0.
ECMA v2
A maintenance release of the standard that included clarifications but defined no new features.
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: Client-side JavaScript
Client-side JavaScript is the name given to JavaScript code that is embedded within an HTML file and executed by a web browser. In addition to the core objects described in the previous section, client-side JavaScript code has access to a number of other objects that represent the web browser, the document displayed in the browser, and the contents of that document. Client-side JavaScript programs are usually event-based, which means that JavaScript event handlers are executed in response to user interactions with the browser and the document. The client-side JavaScript scripting framework is powerful enough to open substantial security holes in web browsers. For this reason, web browsers typically restrict the actions of client-side scripts. This section starts by explaining how JavaScript code is embedded in HTML files, then goes on to introduce the client-side JavaScript objects, JavaScript events and event handling, and JavaScript security restrictions.
JavaScript code may be embedded in HTML files in the form of scripts, event handlers and URLs, as detailed below.
Most JavaScript code appears in HTML files between a <script> tag and a </script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
In JavaScript 1.1 and later you can use the src attribute of the <script> tag to specify the URL of an external script to be loaded and executed. Files of JavaScript code typically have a .js extension. Note that the </script> tag is still required when this attribute is used:
<script src="library.js"></script>
HTML allows scripts to be written in languages other than JavaScript, and some browsers, such as Internet Explorer, support languages such as VBScript. You can use the language attribute to specify what language a script is written in. This attribute defaults to "JavaScript" in all browsers, so you do not usually have to set it. You can also use attribute values such as "JavaScript1.3" and "JavaScript1.5" to specify the version of JavaScript your code uses. Browsers that do not support the specified version of the language simply ignore the script.
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 HTML
JavaScript code may be embedded in HTML files in the form of scripts, event handlers and URLs, as detailed below.
Most JavaScript code appears in HTML files between a <script> tag and a </script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
In JavaScript 1.1 and later you can use the src attribute of the <script> tag to specify the URL of an external script to be loaded and executed. Files of JavaScript code typically have a .js extension. Note that the </script> tag is still required when this attribute is used:
<script src="library.js"></script>
HTML allows scripts to be written in languages other than JavaScript, and some browsers, such as Internet Explorer, support languages such as VBScript. You can use the language attribute to specify what language a script is written in. This attribute defaults to "JavaScript" in all browsers, so you do not usually have to set it. You can also use attribute values such as "JavaScript1.3" and "JavaScript1.5" to specify the version of JavaScript your code uses. Browsers that do not support the specified version of the language simply ignore the script.
HTML 4 does not actually recognize the language attribute of the <script> tag. Instead, the official way to specify the language a script is written in is with the type attribute. For JavaScript, set this attribute to the MIME type "text/javascript":
<script src="functions.js"
        language="JavaScript1.5"
        type="text/javascript"></script>
JavaScript code may also appear as the value of an event handler attribute of an HTML tag. Event handler attribute names always begin with "on". The code specified by one of these attributes is executed when the named event occurs. For example, the following HTML creates a button, and the onclick attribute specifies an event handler that displays an alert (a dialog box) when the user clicks the button:
<input type="button" value="Press Me"
       onclick="alert('Hello World!');">
A list of other available event handler attributes is included later in this 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!
The Window Object
The Window object represents a web browser window. In client-side JavaScript, the Window object is the global object that defines all top-level properties and methods. The properties and methods of the Window object are therefore global properties and global functions and you can refer to them by their property names without any object prefix. One of the properties of the Window object is named window and refers back to the Window object itself:
window           // The global Window object
window.document  // The document property of the window
document         // Or omit the object prefix
See the Window object in the reference section for a full list of its properties and methods. The following sections summarize the most important of these properties and methods and demonstrate key client-side programming techniques using the Window object. Note that the most important property of the Window object is document, which refers to the Document object that describes the document displayed by the browser window. The Document object is described in a section of its own following these window-related subsections.
Three methods allow you to display simple dialog boxes to the user. alert( ) lets you display a message to the user, confirm( ) lets you ask the user a yes-or-no question, and prompt( ) lets you ask the user to enter a single line of text. For example:
alert("Welcome to my home page!"); 
if (confirm("Do you want to play?")) {
    var n = prompt("Enter your name");
}
Most web browsers include a status line at the bottom of the window that is used to display the destination of links and other information. You can specify text to appear in the status line with the status property. The text you set on this property appears in the status area until you or the browser overwrites it with some new value. You can also set defaultStatus to specify text to appear by default when the browser is not displaying any other information in the status line. Here is an HTML hyperlink that uses JavaScript in an event handler to set the status text to something other than the URL of the link:
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 Document Object
Every Window object has a document property that refers to a Document object. The Document object is arguably more important than the Window object itself: while the Window represents the browser window, the Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content. The way that document content is accessed and modified is called the document object model, or DOM, and there are several DOMs in existence:
Legacy DOM
The original legacy document object model evolved along with early versions of the JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
W3C DOM
This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). It is at least partially supported by Netscape 6 and later, Internet Explorer 5 and later, and other modern browsers. The W3C DOM is not closely compatible with the IE 4 DOM, but it does standardize many of the legacy features of the original DOM. This book covers the core features of the standard, and presents a simplified subset of the DOM relevant for JavaScript programmers working with HTML documents. You can find complete coverage in JavaScript: The Definitive Guide.
IE 4 DOM
Microsoft's Internet Explorer Version 4 extended the legacy DOM with powerful new features for accessing and modifying all content of a document. These features were never standardized, but some of them are supported in non-Microsoft browsers.
The following sections explain each of these DOMs in more detail and describe how you can use them to access and modify document content.
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 Legacy DOM
The original client-side JavaScript DOM defines provides access to document content through properties of the Document object. Several read-only properties, such as title, URL, and lastModified provide information about the document as a whole. See the reference section for further details on these and all Document properties and methods. Other properties are arrays that refer to specific types of document content:
forms[ ]
An array of Form objects representing the forms in a document.
images[ ]
An array of Image objects representing the images that appear in a document.
applets[ ]
An array of objects that represent the Java applets embedded in a document. JavaScript can actually be used to script Java and control these applets, but doing so is beyond the scope of this pocket reference.
links[ ]
An array of Link objects representing the hyperlinks in the document.
anchors[ ]
An array of Anchor objects repamed positions created with the name attribute of the HTML <a> tag) in the document.
These arrays contain objects in the order they appear in the document. So the first form in a document is document.forms[0], and the third image is document.images[2]. Another way to refer to document forms, images, and applets is to give them names with the HTML name attribute:
<form name="address">...</form>
When an form, image, or applet is given a name in this way, you can use that name to look it up in the array, or to look it up directly as a property of the document itself:
document.forms["address"]  // A named form
document.address           // The same thing
The Form object is particularly interesting. It has an elements[ ] array that contains objects representing the elements of the form, in the order they appear in the form. See Input, Select, and Textarea in the reference section for details on these form elements.
The elements[ ] array of a Form works much like the forms[ ] array of a Document: it holds form elements in the order they appear in the form, but it also allows them to be referred to by name. Consider this HTML excerpt:
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 W3C DOM
The W3C DOM standardizes most of the features of the legacy DOM, but also adds important new ones. In addition to supporting forms[ ], images[ ], and other array properties of the Document object, it defines methods that allow scripts to access and manipulate any document element, not just special-purpose elements like forms and images.
When creating a document

Return to JavaScript Pocket Reference