Appendix A

JavaScript Language Reference

by Hiro Ruo


CONTENTS

This appendix is a quick reference for the JavaScript language.

Language keywords and symbols are shown in a monospace font. Arguments and other parts to be substituted are in italic monospace.

Optional parts are indicated by brackets. If there are several options that are mutually exclusive, they are shown separated by pipes (|) like this:


[ public | private | protected ] type varname

Reserved Words

The following words are defined as part of the JavaScript language and cannot be used as variable names:

abstract extends interface synchronized
boolean false long this
break final native throw
byte finally new throws
case float null transient
catch for package true
char function private try
class goto protected var
const if public void
continue implements return while
default import short with
do in static  
double instanceof super  
else int switch  

Literals

Literals in JavaScript are represented as follows:

SyntaxDescription
numberInteger (Base10)
0numberInteger (Octal)
0xnumberInteger (Hex)
num1.num2Floating point
num1Enum2Exponential floating point
'characters'String
"characters"String
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\"Double quote
trueBoolean
falseBoolean

Operators

The JavaScript operators are grouped into the following categories: assignment, comparison, arithmetic, string, logical, and bitwise.

Assignment

The following assignment operators are supported in JavaScript:

SyntaxDescription
variable = valueAssignment of value to variable
variable += expressionvariable = variable + expression
variable -= expressionvariable = variable - expression
variable *= expressionvariable = variable * expression
variable /= expressionvariable = variable / expression
variable %= expressionvariable = variable % expression
variable <<= expression variable = variable << expression
variable >>= expression variable = variable >> expression
variable >>>= expression variable = variable >>> expression
variable &= expressionvariable = variable & expression
variable ^= expressionvariable = variable ^ expression
variable |= expressionvariable = variable | expression

Comparison

The following comparison operators are supported in JavaScript:

SyntaxDescription
==Equal
!=Not equal
>Greater than
>=Greater than or equal to
<Less than
<=Less than or equal to

Arithmetic

The following arithmetic operators are supported in JavaScript:

SyntaxDescription
var1 + var2Addition
var1 - var2Subtraction
var1 * var2Multiplication
var1 / var2Division
var1 & var2Modulus
-Negation
var++Postfix increment
++varPrefix increment
var--Postfix decrement
--varPrefix decrement

String

The following string operator is supported in JavaScript:

SyntaxDescription
string1 + string2String concatenation

Logical

The following logical operators are supported in JavaScript:

SyntaxDescription
expr1 && expr2Logical AND
expr1 || expr2Logical OR
!exprLogical NOT

Bitwise

The following bitwise logical operators are supported in JavaScript:

SyntaxDescription
arg1 & arg2Bitwise AND
arg1 | arg2Bitwise OR
arg1 ^ arg2Bitwise XOR
arg1 << arg2Left shift
arg1 >> arg2Right shift
arg1 >>> arg2Zero-fill right shift

Statements

JavaScript provides the traditional conditional and loop statements as well as a set of object manipulation statements.

Conditional Statements

Conditional statements provide the ability to perform steps based on the outcome of a comparison. JavaScript provides this support through the if...else statement.

if...else

The syntax for the if...else statement is as follows:


if (condition) {

   // statements for true condition 

}

else {

   // statements for false condition

}

Loop Statements

Loop statements provide a means for looping through a section of code until an expression evaluates to true (or false).

The for Loop

The for loop will set an initial expression, initExpr, and then loop through a section of JavaScript statements as long as a condition evaluates to true. Each time through the loop, the expression incrExpr is executed:


for (initExpr; condition; incrExpr) {

   // statements to execute while looping

   [break;]

   [continue;]



}

The while Loop

The while loop will continue as long as a specified condition evaluates to true:


while (condition) {

   // statement to execute while looping

   [break;]

   [continue;]

}

Object Manipulation Statements

JavaScript includes several statements that are designed to work with objects.

The for...in Statement

The for...in statement is used to loop through all the properties of an object:


for (variable in object) {

   // statements

   }

The new Statement

The new variable is used to create a new instance of an object:


objectvar = new objecttype ( param1 [, param2] ... [,paramN] )

The with Statement

The with statement is used to set the default object for a series of statements. The properties can then be referred to without using the parent object:


with(object){

   // statements

}

The this Keyword

The this keyword is used to refer to the current object:


this[.property]

The JavaScript Object Hierarchy

The object hierarchy for JavaScript is shown in Figure A.1.

Figure A.1. The JavaScript object hierarchy.Math Object.

The Navigator Object

The Navigator object is used to obtain information about the browser, such as the version number. The Navigator object does not have any methods or event handlers associated with it.

Properties

appCodeName-Used to specify the internal code name of the browser; for example, Atlas.
appName-Used to specify the name of the browser.
appVersion-Used to specify version information for the Navigator object.
userAgent-Used to specify the user-agent header.

The Window Object

The Window object is a top-level object. The Document, Frame, and Location objects are all properties of the Window object.

Properties

defaultStatus-The default message that is displayed in the window's status bar.
frames-An array that reflects all of the frames in a window.
length-The number of frames in a parent window.
name-The name of the current window.
parent-Refers to the parent Window object.
self-Refers to the current window.
status-Used for a temporary status message for the window's status bar. This is used to get or set the status message and overrides defaultStatus.
top-Refers to the topmost window.
window-Refers to the current window.

Methods


alert("message")

Displays a dialog box with the string message and an OK button.


clearTimeout(timeoutID)

Clears a timeout set by SetTimeout. SetTimeout returns timeoutID.


windowReference.close

Closes the window referred to by windowReference.


confirm("message")

Displays a dialog box with the string "message", an OK button, and a Cancel button. Returns true for OK and false for Cancel.


[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])

Opens a new window.


prompt("message" [,"defaultInput"])

Opens a dialog box with a text field for input.


TimeoutID = setTimeout(expression, msec)

Evaluates expression after msec has elapsed.

Event Handlers

onLoad-Occurs when a window finishes loading.
onUnload-Occurs when a window is unloaded.

The Location Object

The Location object contains properties with information about the URL of the current document. This object does not have any methods or event handlers.

Refer to the following sample URL in the property descriptions that follow:


http://www.abc.com/chap1/page2.html#topic3

Properties

hash-The current location's anchor name; in this example, topic3.
host-The hostname:port portion of the URL; in this example, www.abc.com (note that the port is typically the default port and is not shown).
hostname-The host and domain name; in this example, www.abc.com.
href-The entire URL for the current document.
pathname-The path portion of the URL; in this example, /chap1/page2.html.
port-The communications port used on the host computer. Typically the default port.
protocol-The protocol being used (with the colon); in this example, http:.
search-A search query that may be at the end of a URL for a CGI script.

The Frame Object

A window can have several frames. There are no event handlers for a frame.

Properties

frames-An array of all the frames in a window.
name-The <FRAME> tag's NAME attribute.
length-The number of child frames within a frame.
parent-The window or frame containing the current frameset.
self-The current frame.
window-The current frame.

Methods


clearTimeout(timeoutID)

Clears a timeout set by SetTimeout. SetTimeout returns timeoutID.


TimeoutID = setTimeout(expression, msec)

Evaluates expression after msec has elapsed.

The Document Object

The Document object contains information about the current document and provides methods for writing information to the screen.

Properties

alinkColor-Same as the ALINK attribute.
anchors-Array of all the anchors in a document.
bgColor-Same as the BGCOLOR attribute.
cookie-Used to specify a cookie.
fgColor-Same as the TEXT attribute.
forms-An array of all the forms in a document.
lastModified-The date a document was last modified.
linkColor-The same as the LINK attribute.
links-An array of all the links in a document.
location-The complete URL of a document.
referrer-The URL of the calling document.
title-The contents of the <TITLE> tag.
vlinkColor-The VLINK attribute.

Methods


document.clear

Clears the current document.


document.close

Closes an output stream and forces data sent to layout to display.


document.open(["mimeType"])

Opens a stream to collect the output of write or writeln methods.


document.write(expression1 [,expression2], ...[,expressionN])

Writes HTML expressions to a document in the specified window.


document.writeln(expression1 [,expression2], ...[,expressionN])

Writes HTML expressions to a document in the specified window and follows them with a newline.

The anchors Object

An anchor is text in a document that can be the target of a hyperlink. The anchors object has no properties, methods, or event handlers.

Anchors are referenced as follows:


document.anchors[index]

The anchors array has a single property, length, that stores the number of named anchors in the document. This can be referred to as follows:


document.anchors.length

The forms Object

If a document contains several forms, they can be referenced by the forms array. The number of forms is found with the following:


document.forms.length

Each form can be referenced as follows:


document.forms[index]

Properties

action-The ACTION attribute.
elements-An array reflecting all the elements in a form.
encoding-The ENCTYPE attribute.
length-Reflects the number of elements on a form.
method-The METHOD attribute.
target-The TARGET attribute.

Method


formName.submit()

Submits the form named formName.

Event Handler

onSubmit-Occurs when a form is submitted.

The History Object

The History object is used to store information about the previous URLs visited by the user. The list of URLs is stored in chronological order. There are no event handlers associated with the History object.

Property

length-The number of entries in the History object.

Methods


history.back()

Used to reference the previous URL visited (the previous URL in the history list).


history.forward()

Used to reference the next URL in the history list. Until either the user or a script moves backward on the history list, this will have no effect.


history.go(delta | "location")

Used to either move forward or backward delta number of entries on the history list or to go to a specific URL on the history list referred to by location. If delta is used, the reference will be backward if negative and forward if positive. If location is used, the closest URL containing location as a substring will be called.

The links Object

A links object is text or a picture that is specified as a hyperlink. The properties of the links object deal primarily with the URL of the hyperlink. The links object does not have any methods.

The links array contains a list of all the links in a document. The number of links can be found by:


document.links.length

A specific link can be referenced by the array, like this:


document.links[index]

For the descriptions of properties in the following section, the following sample URL is used:


http://www.abc.com/chap1/page2.html#topic3

Properties

hash-The anchor name of the link; in this example, topic3.
host-The hostname:port portion of the URL; in this example, www.abc.com (note that the port is typically the default port and is not shown).
hostname-The host and domain name; in this example, www.abc.com.
href-The entire URL for the link.
pathname-The path portion of the URL; in this example, /chap1/page2.html.
port-The communications port used on the host computer. Typically the default port.
protocol-The protocol being used (with the colon); in this example, http:.
search-A search query that may be at the end of a URL for a CGI script.
target-The same as the TARGET attribute of <LINK>.

Event Handlers

onClick-Occurs when user clicks on the link.
onMouseOver-Occurs when the mouse is moved over the link.

The Math Object

The Math object is a built-in object in JavaScript. The Math object has no event handlers associated with it.

Properties

E-Euler's constant, e, approximately 2.718.
LN2-The natural logarithm of 2, approximately 0.693.
LN10-The natural logarithm of 10, approximately 2.302.
LOG2E-The base 2 logarithm of e, approximately 1.442.
LOG10E-The base 10 logarithm of e, approximately 0.434.
PI-The value of p, approximately 3.14159.
SQRT1_2-The square root of one-half, approximately 0.707.
SQRT2-The square root of 2, approximately 1.414.

Methods


Math.abs(number)

Returns the absolute value of number.


Math.acos(number)

Returns the arc cosine (in radians) of number. The value of number must be between -1 and 1.


Math.asin(number)

Returns the arc sine (in radians) of number. The value of number must be between -1 and 1.


Math.atan(number)

Returns the arc tangent (in radians) of number.


Math.ceil(number)

Returns the lowest integer equal to or greater than number.


Math.cos(number)

Returns the cosine of number.


Math.exp(number)

Returns e number , where e is Euler's constant.


Math.floor(number)

Returns the highest integer equal to or less than number.


Math.log(number)

Returns the natural log of number.


Math.max(num1, num2)

Returns the greater of num1 and num2.


Math.min(num1, num2)

Returns the lesser of num1 and num2.


Math.pow(base, exponent)

Returns the value of base to the exponent power.


Math.random()

Returns a random number between 0 and 1. Note that this works only on UNIX platforms.


Math.round(number)

Returns the value of number rounded to the nearest integer.


Math.sin(number)

Returns the sine of number.


Math.sqrt(number)

Returns the square root of number.


Math.tan(number)

Returns the tangent of number.

The Date Object

The Date object is a built-in object in JavaScript. The Date object has no event handlers or properties associated with it.

Some of the following method examples use the value stored in dateVar as follows:


dateVar = new Date("August 16, 1996 20:45:04");

Methods


dateVar.getDate()

Returns the day of the month (1-31) for dateVar; in this example, 16.


dateVar.getDay()

Returns the day of the week (0=Sunday through 6=Saturday) for dateVar; in this example, 5.


dateVar.getHours()

Returns the hour (0-23) for dateVar; in this example, 20.


dateVar.getMinutes()

Returns the minutes (0-59) for dateVar; in this example, 45.


dateVar.getMonth()

Returns the month (0-11) for dateVar; in this example, 7.


dateVar.getSeconds()

Returns the seconds (0-59) for dateVar; in this example, 4.


dateVar.getTime()

Returns the number of milliseconds since Jan. 1, 1970, 00:00:00.


dateVar.getTimezoneOffset()

Returns the offset in minutes of the current local time to GMT.


dateVar.getYear()

Returns the year for dateVar; in this example, 96.


Date.parse(dateStr)

Parses the string datestr and returns the number of milliseconds since Jan. 1, 1970, 00:00:00.


dateVar.setDate(day)

Sets the day of the month to day for dateVar.


dateVar.setHours(hours)

Sets the hours to hours for dateVar.


dateVar.setMinutes(minutes)

Sets the minutes to minutes for dateVar.


dateVar.setMonth(month)

Sets the month to month for dateVar.


dateVar.setSeconds(seconds)

Sets the seconds to seconds for dateVar.


dateVar.setTime(value)

Sets the time to value, which represents the number of milliseconds since Jan. 1, 1970, 00:00:00.


dateVar.setYear(year)

Sets the year to year for dateVar.


dateVar.toGMTString()

Returns a string representing dateVar as GMT.


dateVar.toLocaleString()

Returns a string representing dateVar in the current time zone.


Date.UTC(year, month, day [,hours] [,minutes] [,seconds])

Returns the number of milliseconds since Jan. 1, 1970, 00:00:00 GMT.

The String Object

Property

length-The length of the string.

Methods


str.anchor(name)

Used to dynamically create an <A> tag. The name parameter is the NAME attribute of the tag.


str.big()

Creates the same effect as the <BIG> tag on the string str.


str.blink()

Creates the same effect as the <BLINK> tag on the string str.


str.bold()

Creates the same effect as the <BOLD> tag on the string str.


str.charAt(a)

Returns the character at position a from the string str.


str.fixed()

Creates the same effect as the <TT> tag on the string str.


str.fontcolor(color)

Creates the same effect as the <FONT COLOR=color> tag.


str.fontsize(size)

Creates the same effect as the <FONTSIZE=size> tag.


str.indexOf(srchStr [,index])

Returns the offset into str of the first appearance of srchStr. The string is searched from left to right. The index parameter can be used to start the search somewhere other than the beginning of the string.


str.italics()

Creates the same effect as the <I> tag on the string str.


str.lastIndexOf(srchStr [, index])

Returns the offset into str of the last occurrence of srchStr. The string is searched from right to left. The index parameter can be used to start the search somewhere other than the end of the string.


str.link(href)

Used to create an HTML link dynamically for the string str. The href parameter is the destination URL for the link.


str.small()

Creates the same effect as the <SMALL> tag on the string str.


str.strike()

Creates the same effect as the <STRIKE> tag on the string str.


str.sub()

Creates a subscript for string str, just like the <SUB> tag.


str.substring(a, b)

Returns the substring of str indicated by the characters between the character at position a and the character at position b. The character count is from left to right starting at 0.


str.sup()

Creates a superscript for string str, just like the <SUP> tag.


str.toLowerCase()

Converts str to lowercase.


str.toUpperCase()

Converts str to uppercase.