BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


JavaScript Pocket Reference
JavaScript Pocket Reference

By David Flanagan

Cover | Table of Contents


Table of Contents

Chapter 1: JavaScript Pocket Reference
The following table specifies what versions of client-side JavaScript are supported by various versions of Netscape Navigator and Microsoft Internet Explorer:
Version
Navigator
Internet Explorer
2
JavaScript 1.0
3
JavaScript 1.1
JavaScript 1.0
4
JavaScript 1.2; not fully ECMA-262 compliant prior to version 4.5
JavaScript 1.2;EMCA-262 compliant
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.
Case sensitivity
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.
Whitespace
JavaScript ignores whitespace between tokens. You may use spaces, tabs, and newlines to format and indent your code in a readable fashion.
Semicolons
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.
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
The following table specifies what versions of client-side JavaScript are supported by various versions of Netscape Navigator and Microsoft Internet Explorer:
Version
Navigator
Internet Explorer
2
JavaScript 1.0
3
JavaScript 1.1
JavaScript 1.0
4
JavaScript 1.2; not fully ECMA-262 compliant prior to version 4.5
JavaScript 1.2;EMCA-262 compliant
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 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.
Case sensitivity
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.
Whitespace
JavaScript ignores whitespace between tokens. You may use spaces, tabs, and newlines to format and indent your code in a readable fashion.
Semicolons
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.
Comments
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.
Identifiers
Variable, function, and label names are JavaScript identifiers. Identifiers are composed of any number of ASCII letters and digits, and the underscore ( _ ) and dollar sign ($) characters. The first character of an identifier must not be a digit, however, and the $ character is not allowed in identifiers in JavaScript 1.0. The following are legal 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!
Variables
Variables are declared, and optionally initialized, with the var statement:
var i;
var j = 1+2+3;
var k,l,m,n;
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.
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, boolean values, and strings. In addition, it supports two compound data types: object and arrays. Functions are also a first class data type in JavaScript, and JavaScript 1.2 adds support for regular expressions (described later) as a specialized type of object.
Numbers
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 octal or hexadecimal notation. An octal literal begins with 0, and a hexadecimal literal begins with 0x:
0377 // The number 255 in octal
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 operations.
Booleans
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.
Strings
A JavaScript string is a sequence of arbitrary letters, digits, and other characters. The ECMA-262 standard requires JavaScript to support the full 16-bit Unicode character set. IE 4 supports Unicode, but Navigator 4 supports only the Latin-1 character set.
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 literal values and variables with JavaScript operators. Parentheses can be used in an expression to group subexpressions and alter the default order of evaluation of the expression. For example:
"1+2
total/n
sum(o.x, a[3])++
(1+2)*3
JavaScript defines a complete set of operators, most of which should be familiar to all C, C++, and Java programmers. In the following table, 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
14
R
++
Unary pre- or post-increment
R
--
Unary pre- or post-decrement
R
-
Unary minus (negation)
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:
Expression 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++
Compound statements
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.
Empty statements
The empty statement is simply a semicolon by itself. It does nothing, and is occasionally useful for coding empty loop bodies.
Labeled statements
In 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
                  
break
The break statement terminates execution of the innermost enclosing loop, or, in JavaScript 1.2, the named loop:
break ;
break label ;  // JavaScript 1.2
case
case is not a true statement. Instead it is a keyword used to label statements within a JavaScript 1.2 switch statement:
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 1.2 supports regular expressions, using the same syntax as Perl 4. A regular expression is specified literally as a sequence of characters within forward slashes (/), or as a JavaScript string passed to the RegExp( ) constructor. The optional g (global search) and i (case-insensitive search) modifiers may follow the second / character, or may be passed to RegExp( ).
The following table summarizes regular expression syntax:
Character
Meaning
\n,\r,\t
Match literal newline, carriage return, tab
\\, \/, \*,
 \+, \?, etc.
Match a special character literally, ignoring or escaping its special 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
\d, \D
Match any digit/non-digit
^, $
Require match at beginning/end of a string, or in multi-line mode, beginning/end of a line
\b,\B
Require match at a word boundarynon-boundary
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
Client-side JavaScript code may be embedded in HTML files in several ways:
<SCRIPT> tag
Most JavaScript code appears in HTML files between a <SCRIPT> tag and a </SCRIPT> tag. The <SCRIPT> tag can also be used to include an external file of JavaScript code into an HTML document. The <SCRIPT> tag supports a number of attributes, including these three important ones:
LANGUAGE
Specifies the scripting language in which the script is written. In most browsers, this attribute defaults to "JavaScript". You must set it if you are mixing scripting languages, such as JavaScript and VBScript.
Set this attribute to "JavaScript1.1" to specify that the code uses JavaScript 1.1 features, and that it should not be interpreted by JavaScript 1.0 browsers. Set this attribute to "JavaScript1.2" to specify that only JavaScript 1.2 browsers should interpret the code. (Note, however, that Navigator 4 has some non-standard behaviors when "JavaScript1.2" is specified.)
SRC
Specifies 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. Supported in JavaScript 1.1 and later.
ARCHIVE
Specifies the URL of a JAR file that contains the script specified by the SRC attribute. Supported in JavaScript 1.2 and later. Archives are required to use Navigator 4 signed scripts.
Event handlers
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 Object Hierarchy
Client-side JavaScript has access to a suite of client-side objects that represent the browser, browser windows and frames, HTML documents, and elements within HTML documents. These objects are structured in a hierarchy as shown in Figure 1.1
Figure 1.1: The client-side object hierarchy
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Windows and Frames
The Window object represents a browser window or frame in client-side JavaScript. Each Window object has properties that refer to its nested frames, if any, and its containing window or frame, if any. Section 1.11 illustrates these properties.
Figure 1.2: Windows and frames
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Forms
One of the powerful features of JavaScript is its ability to manipulate HTML forms. HTML defines the following form elements:
Button (<INPUT TYPE=button>)
A graphical push button; onClick events
Checkbox (<INPUT TYPE=checkbox>)
A toggle button without mutually-exclusive behavior; onClick events
FileUpload (<INPUT TYPE=file>)
A file entry field and file browser; onChange events
Hidden (<INPUT TYPE=hidden>)
A non-visual data field; no event handlers
Option (<OPTION>)
An item within a Select list; event handlers are on the Select object, not Option objects
Password (<INPUT TYPE=password>)
An input field for sensitive data; onChange events
Radio (<INPUT TYPE=radio>)
A toggle button with mutually-exclusive "radio" behavior; onClick events
Reset (<INPUT TYPE=reset>)
A button that resets a form; onClick events
Select (<SELECT[MULTIPLE]> . . . </SELECT>)
A list or drop-down menu from which one or more Option items may be selected; onChange events
Submit (<INPUT TYPE=submit>)
A button that submits a form; onClick events
Text (<INPUT TYPE=text>)
A single-line text entry field;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Events
Client-side JavaScript supports a number of event types. The following table lists the event handlers and the client-side objects that support the handlers. Note that some events, such as onDblClick, are not reliably generated on all platforms.
Event Handler
Supported By
onAbort
Image (JavaScript 1.1)
onBlur,
onFocus
Text elements; Window and all other form elements (1.1)
onChange
Select, text input elements
onClick
Button elements, Link. Return false to cancel default action.
onDblClick
Document, Link, Image, Button elements (1.2)
onError
Image, Window (1.1)
onKeyDown,
onKeyPress,
onKeyUp
Document, Image, Link, text elements (1.2). Return false to cancel.
onLoad,
onUnload
Window; Image in 1.1
onMouseDown,
onMouseUp
Document, Link, Image, Button elements (1.2). Return false to cancel.
onMouseOver,
onMouseOut
Link; Image and Layer (1.2). Return true to prevent URL display.
onReset, onSubmit
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 Security Restrictions
For security reasons, there are restrictions on the tasks that untrusted JavaScript code can perform. In Navigator 4, signed scripts can circumvent these restrictions by requesting certain privileges:
Same origin policy
Scripts can only read properties of windows and documents that were loaded from the same web server unless they have UniversalBrowserRead.
User's browsing history
Scripts cannot read the array of URLs from the History object without UniversalBrowserRead.
File uploads
Scripts cannot set the value property of the FileUpload form element without UniversalBrowserRead.
Sending email and posting news
Scripts cannot submit forms to a mailto: or news: URL without user confirmation or UniversalSendMail.
Closing windows
A script can only close browser windows that itcreated, unless it gets user confirmation or has UniversalBrowserWrite.
Snooping in the cache
A script cannot load any about: URLs, such as about:cache, without UniversalBrowserRead.
Hidden windows and window decorations
A script cannot create small or offscreen windows or windows without a titlebar, and cannot show or hide window decorations without UniversalBrowserWrite.
Intercepting or spoofing events
A script cannot capture events from windows or documents from a different server and cannot set the fields of an Event object without UniversalBrowserWrite.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Global Properties
Core JavaScript defines two global constants:
Infinity
A numeric constant that represents infinity. Internet Explorer 4; ECMA-262; not supported by Navigator 4.
NaN
The not-a-number constant. Internet Explorer 4; ECMA-262; not supported by Navigator 4.
In addition to these core global properties, the Window object defines a number of client-side global properties.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Global Functions
Core JavaScript defines a handful of global functions:
escape (s)
Encode a string for transmission. JavaScript 1.0; ECMA-262; Unicode support in Internet Explorer 4.
eval (code)
Execute JavaScript code from a string.
getClass (javaobj)
Return the JavaClass of a JavaObject. Navigator 3.
isFinite (n)
Determine whether a number is finite. JavaScript 1.2; ECMA-262.
NaN (x)
Check for not-a-number. JavaScript 1.1; ECMA-262.
parseFloat (s)
Convert a string to a number. JavaScript 1.0; enhanced in JavaScript 1.1; ECMA-262.
parseInt (s, radix)
Convert a string to an integer. JavaScript 1.0; enhanced in JavaScript 1.1; ECMA-262.
unescape (s)
Decode an escaped string. JavaScript 1.0; ECMA-262; Unicode support in Internet Explorer 4.
In addition to these core global functions, the Window object defines a number of client-side global methods.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Alphabetical Object Reference
Anchor
the target of a hypertext link
Availability
Client-side JavaScript 1.2
Inherits From
HTMLElement
Synopsis
document.anchors[i]
document.anchors.length
Properties
Anchor inherits properties from HTMLElement and also defines or overrides the following:
name
The name of an anchor.
text
The text of an anchor. Navigator 4.
x
The X-coordinate of an anchor. Navigator 4.
y
The Y-coordinate of an anchor. Navigator 4.
Applet
an applet embedded in a web page
Availability
Client-side JavaScript 1.1
Synopsis
document.applets[i]
document.appletName
Properties
The properties of an Applet object are the same as the public fields of the Java applet it represents.
Methods
The methods of an Applet object are the same as the public methods of the Java applet it represents.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!

Return to JavaScript Pocket Reference