JavaScript Reference
CONTENTS
This section contains an alphabetical listing of the statements available in
JavaScript and their syntax.
Comments are used to include a note within a JavaScript program and are
ignored by the interpreter. There are two different types of comment syntax:
//this is a comment
/* this is also a comment */
Only the second syntax can be used for multiple-line comments; the first must
be repeated on each line.
This statement is used to break out of the current for or
while loop. Control resumes after the loop, as if it had finished.
This statement continues a for or while loop without
executing the rest of the loop. Control resumes at the next iteration of the
loop.
This statement defines a loop, usually to count from one number to another
using an index variable. In this example, the variable i counts from 1
to 9:
for (i=1;i<10;i++;) { statements }
This is a different type of loop, used to iterate through the properties of
an object or the elements of an array. This statement loops through the
properties of the Scores object, using the variable x to hold
each property in turn:
for (x in Scores) { statements }
This statement defines a JavaScript function that can be used anywhere within
the current document. Functions can optionally return a value with the
return statement. This example defines a function to add two numbers
and return the result:
function add(n1,n2) {
result = n1 + n2;
return result;
}
This is a conditional statement. If the condition is true, the statements
after the if statement are executed; otherwise, the statements after
the else statement (if present) are executed. This example prints a
message stating whether a number is less than or greater than 10:
if (a > 10) {
document.write("Greater than 10");
}
else {
document.write("10 or less");
}
A shorthand method can also be used for these types of statements, where
? indicates the if portion and: indicates the else
portion. This statement is equivalent to the previous example:
document.write((a > 10) ? "Greater than 10": "10 or less");
This statement ends a function and optionally returns a value. The
return statement is necessary only if a value is returned.
This statement is used to declare a variable. If you use it within a
function, the variable is guaranteed to be local to that function. If you use it
outside the function, the variable is considered global. Here's an example:
var students = 30;
Because JavaScript is a loosely typed language, you do not need to specify
the type when you declare the variable. A variable is also automatically
declared the first time you assign it a value:
students = 30;
Using var will help avoid conflicts between local and global
variables. Note that arrays are not considered ordinary JavaScript variables;
they are objects.
The while statement defines a loop that iterates as long as a
condition remains true. This example waits until the value of a text field is
"go":
while (document.form1.text1.value != "go") {statements }
The functions in the next sections are built into JavaScript, rather than
being methods of a particular object.
This function evaluates a string as a JavaScript statement or expression, and
either executes it or returns the resulting value. In the example below, a
function is called using variables as an argument:
a = eval("add(x,y);");
eval is typically used to evaluate an expression or statement
entered by the user.
This function finds an integer value at the beginning of a string and returns
it. If there is no number at the beginning of the string, Windows platforms
return 0; other platforms return "NaN" (not a number).
This function finds a floating-point value at the beginning of a string and
returns it. If there is no number at the beginning of the string, either
0 or "NaN" (not a number) is returned.
This function returns true if a value is not a number
("NaN"). This function works on UNIX platforms only.
This function converts a string to URL-encoded (escaped) form. All
nonalphanumeric characters are converted to % and their ASCII value to
hexadecimal.
This function converts an escaped (URL-encoded) string to normal text. It can
be used to convert characters in URLs.
This function taints (marks) a variable or property with the current script's
taint code.
This function removes taint from (unmarks) a variable or property. This only
works if the value carries the current script's taint code. If the value came
from another script or another server, it cannot be untainted.
JavaScript includes a variety of operators that can be used in expressions.
The following operators are used for assignment:
- = uses the variable on the left to store the result of the
expression on the right.
- += adds the number on the right to the variable on the left.
- -= subtracts the number on the right from the variable on the
left.
- *= multiplies the variable by the number on the right.
- /= divides the variable by the number on the right.
- %= uses the modulo operator, described in the next section.
The following operators are used for mathematical expressions:
- + adds two numbers.
- - subtracts one number from another.
- * multiplies two numbers.
- / divides one number by another.
- % (modulo) is the remainder when two numbers are divided.
- - (unary minus) changes a number to its negative version
(complement).
- ++ adds 1 to (increments) a variable. This can be used as either
a prefix or a postfix.
- - subtracts 1 from (decrements) a variable. This can be used as
either a prefix or a postfix.
A single operator works with string values: + concatenates
(combines) two string values.
The following operators are used for conditions and comparisons:
- Equal (==)
- Not equal (!=)
- Less than (<)
- Greater than (>)
- Greater than or equal to (>=)
- Less than or equal to (<=)
The following operators are used for logical expressions using Boolean
values:
These operators are used for binary and bitwise operations:
- And (&) returns one if both of the corresponding bits are
one.
- Or (|) returns one if either of the corresponding bits is one.
- Xor (Exclusive Or) (^) returns one if either, but not both, of
the corresponding bits is one.
- Left shift (<<) shifts the bits in the left operand a
number of positions specified in the right operand.
- Right shift (>>) shifts to the right, including the bit
used to store the sign.
- Zero-fill right shift (>>>) fills to the right, filling
in zeros on the left.
Finally, the following operators are used for working with variables and
functions:
- typeof returns the type of a variable or literal. This is a
string consisting of the values number, string,
boolean, function, object, or undefined.
- void() can be used with a function definition to force it to
evaluate to undefined instead of returning a value.
This is a list of all the keywords, or reserved words, in the JavaScript
language. These may be statements, functions, or connecting words. Some of the
words in this list are not currently used in JavaScript, but have been listed as
reserved words by Netscape because they may be used in a future version.
The main reason for this list is to remind you of which words you cannot use
as variable, function, or object names. Using them may result in unpredictable
behavior.
abstract |
int |
boolean |
interface |
break |
long |
byte |
native |
case |
new |
catch |
null |
char |
package |
class |
private |
const |
protected |
continue |
public |
default |
return |
do |
short |
double |
static |
else |
super |
extends |
switch |
false |
synchronized |
final |
this |
finally |
throw |
float |
throws |
for |
transient |
function |
true |
goto |
try |
if |
var |
implements |
void |
import |
while |
in |
with |
instanceof |
|
You can create a new Array object to define an array-a numbered list
of variables. (Unlike other variables, arrays must be declared.) Use the new
keyword to define an array, as in this example:
students = new Array(30)
Items in the array are indexed beginning with 0. Refer to items in
the array with brackets:
fifth = students[4];
Arrays have a single property, length, which gives the current
number of elements in the array. They have the following methods:
- join quickly joins all the array's elements together, resulting
in a string. The elements are separated by commas, or by the separator you
specify.
- reverse returns a reversed version of the array.
- sort returns a sorted version of the array. Normally, this is an
alphabetical sort; however, you can use a custom sort method by specifying a
comparison routine.
Any string of characters in JavaScript is a string object. The
following statement assigns a variable to a string value:
text = "This is a test."
Because strings are objects, you can also create a new string with the new
keyword:
text = new String("This is a test.");
string objects have a single property, length, which
reflects the current length of the string. There are a variety of methods
available to work with strings:
- anchor() creates an HTML anchor within the current page.
- indexOf() finds an occurrence of a string within the string.
- lastIndexOf() finds an occurrence of a string within the string,
starting at the end of the string.
- link() creates an HTML link using the string's text.
- split() splits the string into an array based on a separator.
- substring() returns a portion of the string.
- toString() can be used on non-string values and converts them to
strings.
- toUpperCase() converts all characters in the string to uppercase.
- toLowerCase() converts all characters in the string to lowercase.
There are also a few methods that enable you to change a string's appearance
when it appears in an HTML document:
- big() displays big text, using the <BIG> tag in
HTML 3.0.
- blink() displays blinking text, using the <BLINK>
tag in Netscape.
- bold() displays bold tag, using the <B> tag.
- fixed() displays fixed-font text, using the <TT>
tag.
- fontcolor() displays the string in a colored font, equivalent to
the <FONTCOLOR> tag in Netscape.
- fontsize() changes the font size, using the <FONTSIZE>
tag in Netscape.
- italics() displays the string in italics, using the <I>
tag.
- small() displays the string in small letters using the <SMALL>
tag in HTML 3.0.
- strike() displays the string in a strikethrough font, using the <STRIKE>
tag.
- sub() displays subscript text, equivalent to the <SUB>
tag in HTML 3.0.
- sup() displays superscript text, equivalent to the <SUP>
tag in HTML 3.0.
As an example, this statement prints the value of the text string in
italics:
document.write(text.italics());
The Math object is not a "real" object, because you can't
create your own objects. Each property or method uses the built-in Math
object. A variety of mathematical constants are available as properties of the Math
object:
- Math.E is the base of natural logarithms (approximately 2.718).
- Math.LN2 is the natural logarithm of two (approximately 0.693).
- Math.LN10 is the natural logarithm of 10 (approximately 2.302).
- Math.LOG2E is the base 2 logarithm of e (approximately 1.442).
- Math.LOG10E is the base 10 logarithm of e (approximately 0.434).
- Math.PI is the ratio of a circle's circumference to its diameter
(approximately 3.14159).
- Math.SQRT1_2 is the square root of one-half (approximately
0.707).
- Math.SQRT2 is the square root of two (approximately 2.7178).
The methods of the Math object enable you to perform mathematical
functions. The methods are listed in the following sections in categories.
Algebraic Functions
- Math.acos() calculates the arc cosine of a number, in radians.
- Math.asin() calculates the arc sine of a number.
- Math.atan() calculates the arc tangent of a number.
- Math.atan2() calculates the polar coordinate angle (theta) for an
x, y coordinate pair.
- Math.cos() calculates the cosine of a number.
- Math.sin() returns the sine of a number.
- Math.tan() calculates the tangent of a number.
Statistical and Logarithmic Functions
- Math.exp() returns e (the base of natural
logarithms) raised to a power.
- Math.log() returns the natural logarithm of a number.
- Math.max() accepts two numbers and returns whichever is greater.
- Math.min() accepts two numbers and returns the smaller of the
two.
For example, this statement assigns the big variable to the larger
of x and y:
big = Math.max(x,y);
Basic Math and Rounding
- Math.abs() calculates the absolute value of a number.
- Math.ceil() rounds a number up to the nearest integer.
- Math.floor() rounds a number down to the nearest integer.
- Math.pow() calculates one number to the power of another.
- Math.round() rounds a number to the nearest integer.
- Math.sqrt() calculates the square root of a number.
As an example, the following statement assigns the x variable to the
square root
of 35:
x = Math.sqrt(25);
Random Numbers
Math.random() returns a random number between 0 and 1.
Note |
The Math.random() method worked only on UNIX platforms until
Netscape 3.0. Be sure you and your users use the latest version.
|
The Date object is a built-in JavaScript object that enables you to
work conveniently with dates and times. You can create a Date object
any time you need to store a date and use the Date object's methods to
work with the date:
Note |
The Date object will not work with dates before January 1st,
1970.
|
- setDate() sets the day of the month.
- setMonth() sets the month. JavaScript numbers the months from 0
to 11, starting with January (0).
- setYear() sets the year.
- setTime() sets the time (and the date) by specifying the number
of milliseconds since January 1st, 1970.
- setHours(), setMinutes(), and setSeconds() set
the time.
- getDate() gets the day of the month.
- getMonth() gets the month.
- getYear() gets the year.
- getTime() gets the time (and the date) as the number of
milliseconds since January 1st, 1970.
- getHours(), getMinutes(), and getSeconds() get
the time.
- getTimeZoneOffset() gives you the local time zone's offset from
GMT.
- toGMTString() converts the date object's time value to text,
using GMT (Greenwich Mean Time, also known as UTC).
- toLocalString() converts the date object's time value to text,
using the user's local time.
- Date.parse() converts a date string, such as "June 20,
1996" to a Date object (number of milliseconds since
1/1/1970).
- Date.UTC() is the opposite; it converts a Date object
value (number of milliseconds) to a UTC (GMT) time.
The navigator object includes information about the current browser
version. At present, it works only with Netscape browsers. Its properties
include the following:
- navigator.appcodeName is the browser's code name, usually "Mozilla".
- navigator.appName is the browser's name, usually "Netscape".
- navigator.appVersion is the version of Netscape being used.
Example: "3.0(Win95;I)".
- navigator.userAgent is the user-agent header, which is sent to
the host when requesting a Web page. It includes the entire version
information-for example, "Mozilla/2.0(Win95;I)".
- navigator.javaEnabled is either true or false,
indicating whether Java (not JavaScript) is enabled on the browser.
- navigator.plugins is an array that contains information about
each currently available plug-in.
- navigator.mimeTypes is an array containing an element for each of
the available MIME types.
The object hierarchy includes objects that represent the browser window, the
current document, and its contents.
The window object represents the current browser window. If multiple
windows are open or frames are used, there may be more than one window object.
These are given aliases to distinguish them:
- self is the current window, as is window. This is the
window containing the current JavaScript document.
- top is the window currently on top (active) on the screen.
- parent is a window that contains frames. Each frame is also a window
object under parent.
- Within a window you have created, opener refers to the window
that opened the window.
- The frames array contains the window object for each
frame. These can be addressed as parent.frames[0] through the
number of frames, or with their individual names, as in parent.docframe.
Each window object includes the following properties:
- defaultStatus is the initial message displayed in the status
line.
- length is the number of frames within a parent window.
- name is the name of the window.
- status is the current value of the status line.
The window object also has three child objects, which you'll look at
in their own sections later:
- The location object stores the location (URL) of the document
displayed in the window.
- The document object holds the Web page itself.
- The history object contains a list of sites visited before or
after the current site in the window.
The window object includes the following methods:
- alert() displays an alert dialog.
- blur() removes focus from the window, sending it to the
background.
- close() closes a window you have opened.
- confirm() displays a confirmation dialog and returns true
or false.
- focus() gives the window focus, moving it to the top.
- open() opens a new window.
- prompt() prompts the user and returns the text entered.
- scroll() scrolls the window, either horizontally or vertically.
The parameters are x and y (column and row)
offset in pixels.
- setTimeout() sets a timeout to execute a statement and returns an
identifier for the timeout.
- clearTimeout() clears the timeout you specify.
Finally, window objects have the following event handlers, which you
can define in the document's <BODY> or <FRAMESET>
tag:
- The onLoad event occurs when the document in the window is
finished loading.
- The onUnload event occurs when another document starts to load,
replacing the window's current document.
- The onFocus event occurs when the window receives focus.
- The onBlur event occurs when the window loses focus.
- The onError event occurs if the document in the window fails to
load properly.
The location object contains information about the current URL being
displayed by the window. It has a set of properties to hold the different
components of the URL:
- location.protocol is the protocol (or method) of the URL.
- location.hostname specifies the host name.
- location.port specifies the communication port.
- location.host is a combination of the host name and port.
- location.pathname is the directory to find the document on the
host, and the name of the file.
- location.hash is the name of an anchor within the document, if
specified.
- location.target specifies the TARGET attribute of the
link that was used to reach the current location.
- location.query specifies a query string.
- location.href is the entire URL.
The location object also has two methods:
- location.reload() reloads the current document; this is the same
as the reload button on Netscape's toolbar.
- location.replace() replaces the current location with a new one;
this is similar to setting the location object's properties.
The history object holds information about the URLs that have been
visited before and after the current one in the window, and it includes methods
to go to previous or next locations:
- history.back() goes back to the previous location.
- history.forward() goes forward to the next location.
- history.go() goes to a specified offset in the history list
(negative numbers go back, positive numbers go forward).
The document object represents the current document in the window
and is a child of the window object. It includes the following
properties:
- bgColor is the background color, specified with the BGCOLOR
attribute.
- fgColor is the foreground (text) color, specified with the TEXT
attribute.
- lastModified is the date the document was last modified. This
date is sent from the server along with the page.
- linkColor is the color used for nonvisited links, specified with
the LINK attribute.
- location specifies the document's URL. Don't confuse this with
the window.location object.
- referrer is the URL of the page the user was viewing prior to the
current page-usually, the page with a link to the current page.
- title is the title of the current page, defined by the HTML <TITLE>
tag.
- vlinkColor is the color for visited links, specified with the VLINK
attribute.
The document object also includes the following child objects as
properties:
- document.forms is an array with an element for each form in the
document. These can also be addressed by name, as in document.regform.
Form elements are child objects of the form object.
- document.links is an array containing elements for each of the
links in the document. It can also contain area objects, used for
client-side image maps.
- document.anchors is an array with elements for each of the
anchors in the document.
- document.images contains an element for each of the images in the
current document.
- document.applets is an array with references to each embedded
Java applet in the document.
The document object has no event handlers. It includes the following
methods:
- clear() clears a document you have closed.
- close() closes a stream and displays any text you have written.
- open() opens a stream and clears the current document.
- write() writes text to the document window.
- writeln() writes text to the document window and adds a carriage
return.
This is a brief summary of the keywords you can use to create your own
objects and customize existing objects.
There are three JavaScript keywords used to create and refer to objects:
- new is used to create a new object.
- this is used to refer to the current object. this can be
used in an object's constructor function or in an event handler.
- with makes an object the default for a group of statements.
Properties without complete object references will refer to this object.
To create a new object, you need an object constructor function. This simply
assigns values to the object's properties using this:
function Name(first,last) {
this.first = first;
this.last = last;
}
You can then create a new object using new:
Fred = new Name("Fred","Smith");
You can also create a generic object using the Object() constructor
and define its properties later:
values = new Object();
You can add additional properties to an object you have created just by
assigning them:
Fred.middle = "Clarence";
Properties you add this way apply only to that instance of the object, not to
all objects of the type. A more permanent approach is to use the prototype
keyword, which adds a property to an object's prototype (definition). This means
that any future object of the type will include this property. You can include a
default value:
Name.prototype.title = "Citizen";
You can use this technique to add properties to the definitions of built-in
objects as well. For example, this statement adds a property called num
to all existing and future string objects, with a default value of 10:
string.prototype.num = 10;