This appendix contains a summary or 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 (except in the array syntax section). If several options are mutually exclusive, they are shown separated by pipes (|) like this:
[ public | private | protected ] type varname
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 |
number | Base 10 Integer (for example, 8) |
0number | Octal Integer (for example, 034) |
0xnumber | Hex Integer (for example, 0x3F8) |
num1.num2 | Floating point (for example, 453.2454) |
num1Enum2 | Exponential floating point (for example, 24.9E6) |
'characters' | String |
"characters" | String |
\b | Backspace |
\f | Form feed |
\n | New line |
\r | Carriage return |
\t | Tab |
\" | Double quote |
true | Boolean |
false | Boolean |
The JavaScript operators are grouped into the following categories: assignment, comparison, arithmetic, string, logical, and bitwise.
variable = value | Assignment of value to variable |
variable += expression | variable = variable + expression |
variable -= expression | variable = variable - expression |
variable *= expression | variable = variable * expression |
variable /= expression | variable = variable / expression |
variable %= expression | variable = variable % expression |
variable <<= expression | variable = variable << expression |
variable >>= expression | variable = variable >> expression |
variable >>>= expression | variable = variable >>> expression |
variable &= expression | variable = variable & expression |
variable ^= expression | variable = variable ^ expression |
variable |= expression | variable = variable | expression |
== | Equal |
!= | Not equal |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
var1 + var2 | Addition |
var1 - var2 | Subtraction |
var1 * var2 | Multiplication |
var1 / var2 | Division |
var1 & var2 | Modulus |
- | Negation |
var++ | Postfix increment |
++var | Prefix increment |
var-- | Postfix decrement |
--var | Prefix decrement |
string1 + string2 | String concatenation |
expr1 && expr2 | Logical AND |
expr1 || expr2 | Logical OR |
!expr | Logical NOT |
arg1 & arg2 | Bitwise AND |
arg1 | arg2 | Bitwise OR |
arg1 ^ arg2 | Bitwise XOR |
arg1 << arg2 | Left shift |
arg1 >> arg2 | Right shift |
arg1 >>> arg2 | Zero-fill right shift |
JavaScript provides the traditional conditional and loop statements as well as a set of object manipulation statements.
if (condition) { // statements for true condition } else { // statements for false condition }
for (initExpr; condition; incrExpr) { // statements to execute while looping [break;] [continue;] } while (condition) { // statements to execute while looping [break;] [continue;] }
for (variable in object) { // statements }
objectvar = new objecttype ( param1 [, param2] ... [,paramN] ); with(object){ // statements }
this[.property]
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.
appCodeName specifies the internal code name of the browserfor example, Atlas.
appName specifies the name of the browser.
appVersion specifies version and host operating system information for the browser.
userAgent specifies the user-agent header.
The following example displays each property of the Navigator object:
<HTML><HEAD> <TITLE>A Navigator Object Example</TITLE> <SCRIPT LANGUAGE="JavaScript"> document.write("appCodeName = " + navigator.appCodeName+ "<BR>"); document.write("appName = " + navigator.appName + "<BR>"); document.write("appVersion = " + navigator.appVersion + "<BR>"); document.write("userAgent = " + navigator.userAgent + "<BR>"); </SCRIPT> </HEAD> <BODY> </BODY> </HTML>
The window object is a top-level object. The document, frame, and location objects are all properties of the window object.
defaultStatus is the default message that displays in the window's status bar.
frames is an array that reflects all the frames in a window.
length is the number of frames in a parent window.
name is the name of the current window.
parent refers to the parent window object.
self refers to the current window.
status holds a temporary status message for the window's status bar. This property gets or set the status message and overrides defaultStatus.
top refers to the topmost window.
window refers to the current window.
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.
onLoad occurs when a window finishes loading.
onUnload occurs when a window is unloaded.
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
hash is the current location's anchor name, such as topic3.
host is the hostname:port portion of the URL, such as www.abc.com. (Note that the port is typically the default port and not shown in the preceding example.)
hostname is the host and domain name, such as www.abc.com.
href is the entire URL for the current document.
pathname is the path portion of the URL, such as /chap1/page2.html.
port is the communications port used on the host computer (typically the default port).
protocol is the protocol being used (with the colon), such as http:.
search is a search query that may be at the end of an URL for a CGI script.
A window can have several frames. The frames can scroll independently, and each can have a unique URL. A frame has no event handlers. The onLoad and onUnload events are for the window object.
frames is an array of all the frames in a window.
name is the <FRAME> tag's NAME attribute.
length is the number of child frames within a frame.
parent is the window or frame containing the current frameset.
self is the current frame.
window is the current frame.
clearTimeout(timeoutID)
Clears a timeout set by SetTimeout. SetTimeout returns timeoutID.
TimeoutID = setTimeout(expression, msec)
Evaluates expression after msec has elapsed.
The document object contains information about the current document and provides methods for writing information to the screen. The document object is created by the <BODY></BODY> tag pair. Several of the properties reflect attributes
associated with the <BODY> tag.
The anchor, form, history, and link objects are properties of the document object.
alinkColor is the same as the ALINK attribute.
anchors is an array of all the anchors in a document.
bgColor is the same as the BGCOLOR attribute.
cookie specifies a cookie.
fgColor is the same as the TEXT attribute.
forms is an array of all the forms in a document.
lastModified is the date a document was last modified.
linkColor is the same as the LINK attribute.
links is an array of all the links in a document.
location is the complete URL of a document.
referrer is the URL of the calling document.
title is the contents of the <TITLE> tag.
vlinkColor is the VLINK attribute.
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 the 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.
An anchor is text in a document that can be the target of a hyperlink. The anchor is defined with the <A></A> tag pair. The anchor object has no properties, methods, or event handlers. The anchors array references each named anchor in a
document. Anchors are referenced as follows:
document.anchors[index]
The anchors array has a single property, length, which stores the number of named anchors in the document. You can refer to this property as follows:
document.anchors.length
Forms are created with the <FORM></FORM> tag pair. Most of the form object's properties reflect attributes of the <FORM> tag. The form object also has several objects as properties:
If a document contains several forms, you can reference them with the forms array. You find the number of forms with the following:
document.forms.length
Each form can be referenced as follows:
document.forms[index]
action is the ACTION attribute.
elements is an array reflecting all the elements in a form.
encoding is the ENCTYPE attribute.
length reflects the number of elements on a form.
method is the METHOD attribute.
target is the TARGET attribute.
formName.submit()
Submits the form named formName.
onSubmit occurs when a form is submitted.
The history object stores information about the previous URLs visited by the user. The list of URLs is stored in chronological order. The history object has no event handlers.
length is the number of entries in the history object.
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 backwards on the history list, this has 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 is backward if negative and forward if positive. If location is used, the closest URL containing location as a substring is called.
A link object is text or a picture that is specified as a hyperlink. The properties of the link object deal primarily with the URL of the hyperlink. The link object does not have any methods.
The links array contains a list of all the links in a document. You can find the number of links with the following line:
document.links.length()
A specific link can be referenced by the following array:
document.links[index]
Refer to the following sample URL for the link object's properties descriptions:
http://www.abc.com/chap1/page2.html#topic3
hash is the anchor name of the link, such as topic3.
host is the hostname:port portion of the URL, such as www.abc.com. (Note that the port is typically the default port and is not shown in the preceding example.)
hostname is the host and domain name, such as www.abc.com.
href is the entire URL for the link.
pathname is the path portion of the URL, such as /chap1/page2.html.
port is the communications port used on the host computer (typically the default port).
protocol is the protocol with the colon, such as http:.
search is a search query that may be at the end of an URL for a CGI script.
target is the same as the TARGET attribute of <LINK>.
onClick occurs when user clicks the link.
onMouseOver occurs when the mouse moves over the link.
The math object is built in to JavaScript. This object's properties contain many common mathematical constants. The math methods provide a wide array of trigonometric and other mathematical functions. The math object has no event handlers.
The reference to number in the methods can be either a number or an expression that evaluates to a valid number.
E is Euler's constant, approximately 2.718.
LN2 is the natural logarithm of two, approximately 0.693.
LN10 is the natural logarithm of ten, approximately 2.302.
LOG2E is the base 2 logarithm of e, approximately 1.442.
LOG10E is the base 10 logarithm of e, approximately 0.434.
SQRT1_2 the square root of one half, approximately 0.707.
SQRT2 the square root of 2, approximately 1.414.
Math.abs(number)
Returns the absolute value of number.
Math.acos(number)
Returns the arc cosine (in radians) of number. The value number must be between -1 and 1.
Math.asin(number)
Returns the arc sine (in radians) of number. The value number must be between -1 and 1.
Math.atan(number)
Returns the arc tan (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[
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 method 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 is built in to JavaScript. This object provides many useful methods for getting and dealing with the time and date. The date object has no properties or event handlers associated with it.
Most of the date methods have a date object associated with it. The following method definitions use a date object named dateVar. The examples for many of the methods use the value stored in dateVar as follows:
dateVar = new Date("August 16, 1996 20:45:04");
dateVar.getDate()
Returns the day of the month (1-31) for dateVar, such as 16.
dateVar.getDay()
Returns the day of the week (0 for Sunday through 6 for Saturday) for dateVar, such as 5.
dateVar.getHours()
Returns the hour (0-23) for dateVar, such as 20.
dateVar.getMinutes()
Returns the minutes (0-59) for dateVar, such as 45.
dateVar.getMonth()
Returns the month (0-11) for dateVar, such as 7.
dateVar.getSeconds()
Returns the seconds (0-59) for dateVar, such as 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, such as 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 is built in to JavaScript. This object provides many string-manipulation methods. The only property for the string object is the length.
The string object has no event handlers.
length is the length of the string.
str.anchor(name)
Used to dynamically create a <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
Returns the a
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 <FONT SIZE=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 a 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 a
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.