Web DevCenter    
 Published on Web DevCenter (http://www.oreillynet.com/javascript/)
 See this if you're having trouble printing code examples


Core JavaScript Reference: Chapter 24 - JavaScript: The Definitive Guide

by David Flanagan

This part of the book is a reference that documents the classes, methods, and properties defined by the core JavaScript language. This introduction and the sample reference page that follows explain how to use and get the most out of this section. Take the time to read this material carefully, and you will find it easier to locate and use the information you need!

JavaScript: The Definitive Guide book cover

This excerpt is from JavaScript: The Definitive Guide. The indispensable reference for JavaScript programmers since 1996, JavaScript: The Definitive Guide, 5th Edition is completely revised and expanded to cover JavaScript as it is used in today's Web 2.0 applications.

buy button

This reference is arranged alphabetically. The reference pages for the methods and properties of classes are alphabetized by their full names, which include the names of the classes that define them. For example, if you want to read about the replace( ) method of the String class, you would look under String.replace( ), not just replace.

Core JavaScript defines some global functions and properties, such as eval( ) and NaN. Technically, these are properties of the global object. Since the global object has no name, however, they are listed in this reference section under their own unqualified names. For convenience, the full set of global functions and properties in core JavaScript is summarized in a special reference page named "Global" (even though there is no object or class by that name).

Once you've found the page you're looking for, you shouldn't have much difficulty finding the information you need. Still, you'll be able to make better use of this reference if you understand how the reference pages are written and organized. What follows is a sample reference page titled Sample Entry that demonstrates the structure of each reference page and tells you where to find various types of information within the pages. Take the time to read this page before diving into the rest of the reference material.

Name

Sample Entry: how to read these reference pages — Availability: Inherits from

Title and Short Description

Every reference entry begins with a four-part title block like that above. The entries are alphabetized by title. The short description, shown below the title, gives you a quick summary of the item documented in the entry; it can help you quickly decide if you're interested in reading the rest of the page.

Availability

The availability information is shown in the upper-right corner of the title block. In earlier versions of this book, this information told you what version of what web browsers supported the item being documented. Today, most browsers support most of the items documented in this book, and this availability section is more likely to tell you what standard provides the formal specification for the item. You might see "ECMAScript v1" or "DOM Level 2 HTML" here, for example. If the item has been deprecated, that is noted here, as well.

Browser names and version numbers do sometimes appear here, typically when the item being documented is a cutting-edge feature that is not universally adopted or when the item is an Internet Explorer-specific feature.

If an item, such as the History object, has never been standardized but is well supported in browsers that support a particular version of JavaScript, then this section may list that JavaScript version number. The History object, for example, has an availability of "JavaScript 1.0".

If the entry for a method does not include any availability information, that means that it has the same availability as the class that defines the method.

Inherits from

If a class inherits from a superclass or a method overrides a method in a superclass, that information is shown in the lower-right corner of the title block.

As described in Chapter 9, Classes, Constructors, and Prototypes, JavaScript classes can inherit properties and methods from other classes. For example, the String class inherits from Object, and HTMLDocument inherits from Document, which inherits from Node. The entry for String summarizes this inheritance as "Object → String", and the entry for HTMLDocument says "Node → Document → HTMLDocument". When you see this inheritance information, you may also want to look up the listed superclasses.

When a method has the same name as a method in a superclass, the method overrides the superclass's method. See Array.toString( ) for an example.

Constructor

If the reference page documents a class, and the class has a constructor, this section shows you how to use the constructor method to create instances of the class. Since constructors are a type of method, the Constructor section looks a lot like the Synopsis section of a method's reference page.

Synopsis

Reference pages for functions, methods, and properties have a Synopsis section that shows how you might use the function, method, or property in your code. The reference entries in this book use two different styles of synopses. The entries in the core JavaScript reference and the client-side entries that document methods (such as Window methods) that are not related to the DOM use untyped synopses. For example, the synopsis for the Array.concat( ) method is:

array.concat(value,...)

The italic font indicates text that is to be replaced with something else. array should be replaced with a variable or JavaScript expression that holds or evaluates to an array. And value is simply a name for an argument to be passed to the method. This named argument is decribed later in the synopsis, and that description contains information about the type and purpose of the argument. The ellipsis (...) indicates that this method can take any number of value arguments. Because the terms concat and the open and close parentheses are not in italics, you must include them exactly as shown in your JavaScript code.

Many of the methods documented in the client-side JavaScript section have been standardized by the W3C, and their specifications include definitive type information for method arguments and method return values. These entries include this type information in the synopsis. The synopsis for the Document.getElementById( ) method, for example is:

Element getElementById(StringelementId);

This synopsis uses Java-style syntax to indicate that the getElementById( ) method returns an Element object and expects one string argument named elementId. Because this is a method of Document, it is implicit that it is invoked on a document, and no document prefix is included.

Arguments

If a reference page documents a function, a method, or a class with a constructor method, the Constructor or Synopsis section is followed by an Arguments subsection that describes the arguments to the method, function, or constructor. If there are no arguments, this subsection is simply omitted:

arg1

The arguments are described in a list here. This is the description for argument arg1, for example.

arg2

And this is the description for argument arg2.

Returns

If a function or method has a return value, this subsection explains that value.

Throws

If a constructor, function, or method can throw an exception, this subsection lists the types of exceptions that may be thrown and explains the circumstances under which this can occur.

Constants

Some classes define a set of constants that serve as the values for a property or as the arguments to a method. The Node interface, for example, defines important constants to serve as the set of legal values for its nodeType property. When an interface defines constants, they are listed and documented in this section. Note that constants are static properties of the class itself, not of instances of that class

Properties

If the reference page documents a class, the Properties section lists the properties defined by the class and provides short explanations of each. In Part III, “Core JavaScript Reference”, each property also has a complete reference page of its own. In Part IV, “Client-Side JavaScript Reference”, most properties are fully described in this properties list. The most important or complex client-side properties do have a page of their own, and this is noted here. In Part IV, “Client-Side JavaScript Reference”, the properties of DOM-related classes include type information. Properties of other classes and all properties in Part III, “Core JavaScript Reference” are untyped. The property listing looks like this:

prop1

This is a summary of untyped property prop1. Only the property name is listed above, but this description will tell you the property's type, its purpose or meaning, and whether it is read-only or read/write.

readonly integer prop2

This is a summary for a typed property prop2. The property name is included along with its type. This descriptive paragraph explains the purpose of the property.

Methods

The reference page for a class that defines methods includes a Methods section. It is just like the Properties section, except that it summarizes methods instead of properties. All methods also have reference pages of their own. This summary section lists only method names. Argument type and return type information can be found on the method's reference page.

Description

Most reference pages contain a Description section, which is the basic description of the class, method, function, or property that is being documented. This is the heart of the reference page. If you are learning about a class, method, or property for the first time, you may want to skip directly to this section and then go back and look at previous sections, such as Arguments, Properties, and Methods. If you are already familiar with a class, method, or property, you probably won't need to read this section and instead will just want to quickly look up some specific bit of information (for example, from the Arguments or Properties sections).

In some entries, this section is no more than a short paragraph. In others, it may occupy a page or more. For some simple methods, the Arguments and Returns sections document the method sufficiently by themselves, so the Description section is omitted.

Example

Some pages include an example that shows typical usage. Most pages do not contain examples, however; you'll find those in first half of this book.

Bugs

When an item doesn't work quite right, this section describes the bugs. Note, however, that this book does not attempt to catalog every bug.

See Also

Many reference pages conclude with cross-references to related reference pages that may be of interest. Sometimes reference pages also refer back to one of the main chapters of the book.


Name

arguments[ ]: an array of function arguments — ECMAScript v1

Synopsis

arguments

Description

The arguments[] array is defined only within a function body. Within the body of a function, arguments refers to the Arguments object for the function. This object has numbered properties and serves as an array containing all arguments passed to the function. The arguments identifier is essentially a local variable automatically declared and initialized within every function. It refers to an Arguments object only within the body of a function and is undefined in global code.

See Also

Arguments;Chapter 8, Functions

Name

Arguments: arguments and other properties of a function — ECMAScript v1: Object → Arguments

Synopsis

arguments

arguments[n]

Elements

The Arguments object is defined only within a function body. Although it is not technically an array, the Arguments object has numbered properties that function as array elements and a length property that specifies the number of array elements. Its elements are the values that are passed as arguments to the function. Element 0 is the first argument, element 1 is the second argument, and so on. All values passed as arguments become array elements of the Arguments object, whether or not those arguments are given names in the function declaration.

Properties

callee

A reference to the function that is currently executing.

length

The number of arguments passed to the function and the number of array elements in the Arguments object.

Description

When a function is invoked, an Arguments object is created for it, and the local variable arguments is automatically initialized to refer to that Arguments object. The main purpose of the Arguments object is to provide a way to determine how many arguments are passed to the function and to refer to unnamed arguments. In addition to the array elements and length property, however, the callee property allows an unnamed function to refer to itself.

For most purposes, the Arguments object can be thought of as an array with the addition of the callee property. However, it is not an instance of Array, and the Arguments.length property does not have any of the special behaviors of the Array.length property and cannot be used to change the size of the array.

The Arguments object has one very unusual feature. When a function has named arguments, the array elements of the Arguments object are synonyms for the local variables that hold the function arguments. The Arguments object and the argument names provide two different ways of referring to the same variable. Changing the value of an argument with an argument name changes the value that is retrieved through the Arguments object, and changing the value of an argument through the Arguments object changes the value that is retrieved by the argument name.

See Also

Function; Chapter 8, Functions


Name

Arguments.callee: the function that is currently running — ECMAScript v1

Synopsis

arguments.callee

Description

arguments.callee refers to the function that is currently running. It provides a way for an unnamed function to refer to itself. This property is defined only within a function body.

Example

// An unnamed function literal uses the callee property to refer
// to itself so that it can be recursive
var factorial = function(x) {
    if (x < 2) return 1;
    else return x * arguments.callee(x-1);
}
var y = factorial(5);  // Returns 120

Name

Arguments.length: the number of arguments passed to a function — ECMAScript v1

Synopsis

arguments.length

Description

The length property of the Arguments object specifies the number of arguments passed to the current function. This property is defined only within a function body.

Note that this property specifies the number of arguments actually passed, not the number expected. See Function.length for the number of declared arguments. Note also that this property does not have any of the special behavior of the Array.length property.

Example

// Use an Arguments object to check that correct # of args were passed
function check(args) {
    var actual = args.length;           // The actual number of arguments
    var expected = args.callee.length;  // The expected number of arguments
    if (actual != expected) {           // Throw exception if they don't match
        throw new Error("Wrong number of arguments: expected: " +
                         expected + "; actually passed " + actual);
    }
}
// A function that demonstrates how to use the function above
function f(x, y, z) {
    check(arguments);  // Check for correct number of arguments
    return x + y + z;  // Now do the rest of the function normally
}

See Also

Array.length, Function.length

Name

Array: built-in support for arrays — ECMAScript v1: Object → Array

Constructor

new Array( )

new Array(size)

new Array(element0, element1, ..., elementn)

Arguments

size

The desired number of elements in the array. The returned array has its length field set to size.

element0, ... elementn

An argument list of two or more arbitrary values. When the Array( ) constructor is invoked with these arguments, the newly created array is initialized with the specified argument values as its elements and its length field set to the number of arguments.

Returns

The newly created and initialized array. When Array( ) is invoked with no arguments, the returned array is empty and has a length field of 0. When invoked with a single numeric argument, the constructor returns an array with the specified number of undefined elements. When invoked with any other arguments, the constructor initializes the array with the values specified by the arguments. When the Array( ) constructor is called as a function, without the new operator, it behaves exactly as it does when called with the new operator.

Throws

RangeError

When a single integer size argument is passed to the Array( ) constructor, a RangeError exception is thrown if size is negative or is larger than 232−1.

Literal Syntax

ECMAScript v3 specifies an array literal syntax. You may also create and initialize an array by placing a comma-separated list of expressions within square brackets. The values of these expressions become the elements of the array. For example:

var a = [1, true, 'abc'];
var b = [a[0], a[0]*2, f(x)];

Properties

length

A read/write integer specifying the number of elements in the array or, when the array does not have contiguous elements, a number one larger than the index of the last element in the array. Changing the value of this property truncates or extends the array.

Methods

concat( )

Concatenates elements to an array.

join( )

Converts all array elements to strings and concatenates them.

pop( )

Removes an item from the end of an array.

push( )

Pushes an item to the end of an array.

reverse( )

Reverses, in place, the order of the elements of an array.

shift( )

Shifts an element off the beginning of an array.

slice( )

Returns a subarray slice of an array.

sort( )

Sorts, in place, the elements of an array.

splice( )

Inserts, deletes, or replaces array elements.

toLocaleString( )

Converts an array to a localized string.

toString( )

Converts an array to a string.

unshift( )

Inserts elements at the beginning of an array.

Description

Arrays are a basic feature of JavaScript and are documented in detail in Chapter 7, Objects and Arrays.


Name

Array.concat( ): concatenate arrays — ECMAScript v3

Synopsis

array.concat(value, ...)

Arguments

value, ...

Any number of values to be concatenated with array.

Returns

A new array, which is formed by concatenating each of the specified arguments to array.

Description

concat( ) creates and returns a new array that is the result of concatenating each of its arguments to array. It does not modify array. If any of the arguments to concat( ) is itself an array, the elements of that array are concatenated, rather than the array itself.

Example

var a = [1,2,3];
a.concat(4, 5)          // Returns [1,2,3,4,5]
a.concat([4,5]);        // Returns [1,2,3,4,5]
a.concat([4,5],[6,7])   // Returns [1,2,3,4,5,6,7]
a.concat(4, [5,[6,7]])  // Returns [1,2,3,4,5,[6,7]]

See Also

Array.join( ), Array.push( ), Array.splice( )

Name

Array.join( ): concatenate array elements to form a string — ECMAScript v1

Synopsis

array.join( )

array.join(separator)

Arguments

separator

An optional character or string used to separate one element of the array from the next in the returned string. If this argument is omitted, a comma is used.

Returns

The string that results from converting each element of array to a string and then concatenating them together, with the separator string between elements.

Description

join( ) converts each element of an array to a string and then concatenates those strings, inserting the specified separator string between the elements. It returns the resulting string.

You can perform a conversion in the opposite direction—splitting a string into array elements—with the split( ) method of the String object. See String.split( ) for details.

Example

a = new Array(1, 2, 3, "testing");
s = a.join("+");  // s is the string "1+2+3+testing"

See Also

String.split( )

Name

Array.length: the size of an array — ECMAScript v1

Synopsis

array.length

Description

The length property of an array is always one larger than the index of the highest element defined in the array. For traditional "dense" arrays that have contiguous elements and begin with element 0, the length property specifies the number of elements in the array.

The length property of an array is initialized when the array is created with the Array( ) constructor method. Adding new elements to an array updates the length, if necessary:

a = new Array( );                         // a.length initialized to 0
b = new Array(10);                       // b.length initialized to 10
c = new Array("one", "two", "three");    // c.length initialized to 3
c[3] = "four";                           // c.length updated to 4
c[10] = "blastoff";                      // c.length becomes 11

You can set the value of the length property to change the size of an array. If you set length to be smaller than its previous value, the array is truncated, and elements at the end are lost. If you set length to be larger than its previous value, the array becomes bigger, and the new elements added at the end of the array have the undefined value.


Name

Array.pop( ): remove and return the last element of an array — ECMAScript v3

Synopsis

array.pop( )

Returns

The last element of array.

Description

pop( ) deletes the last element of array, decrements the array length, and returns the value of the element that it deleted. If the array is already empty, pop( ) does not change the array and returns the undefined value.

Example

pop( ), and its companion method push( ), provide the functionality of a first-in, last-out stack. For example:

var stack = [];       // stack: []
stack.push(1, 2);     // stack: [1,2]     Returns 2
stack.pop( );            // stack: [1]       Returns 2
stack.push([4,5]);      // stack: [1,[4,5]] Returns 2
stack.pop( )             // stack: [1]       Returns [4,5]
stack.pop( );            // stack: []        Returns 1

See Also

Array.push( )


Name

Array.push( ): append elements to an array — ECMAScript v3

Synopsis

array.push(value, ...)

Arguments

value, ...

One or more values to be appended to the end of array.

Returns

The new length of the array, after the specified values are appended to it.

Description

push( ) appends its arguments, in order, to the end of array. It modifies array directly, rather than creating a new array. push( ), and its companion method pop( ), use arrays to provide the functionality of a first in, last out stack. See Array.pop( ) for an example.

See Also

Array.pop( )

Name

Array.reverse( ): reverse the elements of an array — ECMAScript v1

Synopsis

array.reverse( )

Description

The reverse( ) method of an Array object reverses the order of the elements of an array. It does this in place: it rearranges the elements of the specified array without creating a new array. If there are multiple references to array, the new order of the array elements is visible through all references.

Example

a = new Array(1, 2, 3);    // a[0] == 1, a[2] == 3;
a.reverse( );               // Now a[0] == 3, a[2] == 1;

Name

Array.shift( ): shift array elements down — ECMAScript v3

Synopsis

array.shift( )

Returns

The former first element of the array.

Description

shift( ) removes and returns the first element of array, shifting all subsequent elements down one place to occupy the newly vacant space at the start of the array. If the array is empty, shift( ) does nothing and returns the undefined value. Note that shift( ) does not create a new array; instead, it modifies array directly.

shift( ) is similar to Array.pop( ), except it operates on the beginning of an array rather than the end. shift( ) is often used in conjunction with unshift( ).

Example

var a = [1, [2,3], 4]
a.shift( );  // Returns 1; a = [[2,3], 4]
a.shift( );  // Returns [2,3]; a = [4]

See Also

Array.pop( ), Array.unshift( )

Name

Array.slice( ): return a portion of an array — ECMAScript v3

Synopsis

array.slice(start, end)

Arguments

start

The array index at which the slice is to begin. If negative, this argument specifies a position measured from the end of the array. That is, −1 indicates the last element, −2 indicates the next from the last element, and so on.

end

The array index immediately after the end of the slice. If not specified, the slice includes all array elements from the start to the end of the array. If this argument is negative, it specifies an array element measured from the end of the array.

Returns

A new array that contains the elements of array from the element specified by start, up to, but not including, the element specified by end.

Description

slice( ) returns a slice, or subarray, of array. The returned array contains the element specified by start and all subsequent elements up to, but not including, the element specified by end. If end is not specified, the returned array contains all elements from the start to the end of array.

Note that slice( ) does not modify the array. If you want to actually remove a slice of an array, use Array.splice( ).

Example

var a = [1,2,3,4,5];
a.slice(0,3);    // Returns [1,2,3]
a.slice(3);      // Returns [4,5]
a.slice(1,-1);   // Returns [2,3,4]
a.slice(-3,-2);  // Returns [3]; buggy in IE 4: returns [1,2,3]

Bugs

start can't be a negative number in Internet Explorer 4. This is fixed in later versions of IE.

See Also

Array.splice( )

Name

Array.sort( ): sort the elements of an array — ECMAScript v1

Synopsis

array.sort( ) array.sort(orderfunc)

Arguments

orderfunc

An optional function used to specify the sorting order.

Returns

A reference to the array. Note that the array is sorted in place, and no copy is made.

Description

The sort( ) method sorts the elements of array in place: no copy of the array is made. If sort( ) is called with no arguments, the elements of the array are arranged in alphabetical order (more precisely, the order determined by the character encoding). To do this, elements are first converted to strings, if necessary, so that they can be compared.

If you want to sort the array elements in some other order, you must supply a comparison function that compares two values and returns a number indicating their relative order. The comparison function should take two arguments, a and b, and should return one of the following:

  • A value less than zero, if, according to your sort criteria, a is less than b and should appear before b in the sorted array.

  • Zero, if a and b are equivalent for the purposes of this sort.

  • A value greater than zero, if a is greater than b for the purposes of the sort.

Note that undefined elements of an array are always sorted to the end of the array. This is true even if you provide a custom ordering function: undefined values are never passed to the orderfunc you supply.

Example

The following code shows how you might write a comparison function to sort an array of numbers in numerical, rather than alphabetical order:

// An ordering function for a numerical sort
function numberorder(a, b) { return a - b; }
a = new Array(33, 4, 1111, 222);
a.sort( );               // Alphabetical sort: 1111, 222, 33, 4
a.sort(numberorder);    // Numerical sort: 4, 33, 222, 1111

Name

Array.splice( ): insert, remove, or replace array elements — ECMAScript v3

Synopsis

array.splice(start, deleteCount, value, ...)

Arguments

start

The array element at which the insertion and/or deletion is to begin.

deleteCount

The number of elements, starting with and including start, to be deleted from array. Specify 0 to insert elements without deleting any.

value, ...

Zero or more values to be inserted into array, beginning at the index specified by start.

Returns

An array containing the elements, if any, deleted from array.

Description

splice( ) deletes zero or more array elements starting with and including the element start and replaces them with zero or more values specified in the argument list. Array elements that appear after the insertion or deletion are moved as necessary so that they remain contiguous with the rest of the array. Note that, unlike the similarly named slice( ), splice( ) modifies array directly.

Example

The operation of splice( ) is most easily understood through an example:

var a = [1,2,3,4,5,6,7,8]
a.splice(1,2);      // Returns [2,3]; a is [1,4]
a.splice(1,1);      // Returns [4]; a is [1]
a.splice(1,0,2,3);  // Returns []; a is [1 2 3]

See Also

Array.slice( )

Name

Array.toLocaleString( ): convert an array to a localized string — ECMAScript v1: Overrides Object.toLocaleString( )

Synopsis

array.toLocaleString( )

Returns

A localized string representation of array.

Throws

TypeError

If this method is invoked on an object that is not an Array.

Description

The toLocaleString( ) method of an array returns a localized string representation of an array. It does this by calling the toLocaleString( ) method of all of the array elements, then concatenating the resulting strings using a locale-specific separator character.

See Also

Array.toString( ), Object.toLocaleString( )

Name

Array.toString( ): convert an array to a string — ECMAScript v1: Overrides Object.toString( )

Synopsis

array.toString( )

Returns

A string representation of array.

Throws

TypeError

If this method is invoked on an object that is not an Array.

Description

The toString( ) method of an array converts an array to a string and returns the string. When an array is used in a string context, JavaScript automatically converts it to a string by calling this method. On some occasions, however, you may want to call toString( ) explicitly.

toString( ) converts an array to a string by first converting each array element to strings (by calling its toString( ) method). Once each element is converted to a string, toString( ) outputs them in a comma-separated list. This return value is the same string that would be returned by the join( ) method with no arguments.

See Also

Array.toLocaleString( ), Object.toString( )

Name

Array.unshift( ): insert elements at the beginning of an array — ECMAScript v3

Synopsis

array.unshift(value, ...)

Arguments

value, ...

One or more values that are inserted at the start of array.

Returns

The new length of the array.

Description

unshift( ) inserts its arguments at the beginning of array, shifting the existing elements to higher indexes to make room. The first argument to shift( ) becomes the new element 0 of the array; the second argument, if any, becomes the new element 1; and so on. Note that unshift( ) does not create a new array; it modifies array directly.

Example

unshift( ) is often used in conjunction with shift( ). For example:

var a = [];             // a:[]
a.unshift(1);           // a:[1]          Returns: 1
a.unshift(22);          // a:[22,1]       Returns: 2
a.shift( );                // a:[1]          Returns: 22
a.unshift(33,[4,5]);    // a:[33,[4,5],1] Returns: 3

See Also

Array.shift( )

Name

Boolean: support for boolean values — ECMAScript v1: Object → Boolean

Constructor

new Boolean(value) // Constructor function
Boolean(value)     // Conversion function

Arguments

value

The value to be held by the Boolean object or to be converted to a boolean value.

Returns

When invoked as a constructor with the new operator, Boolean( ) converts its argument to a boolean value and returns a Boolean object that contains that value. When invoked as a function, without the new operator, Boolean( ) simply converts its argument to a primitive boolean value and returns that value.

The values 0, NaN, null, the empty string "", and the undefined value are all converted to false. All other primitive values, except false (but including the string "false"), and all objects and arrays are converted to true.

Methods

toString( )

Returns "true" or "false", depending on the boolean value represented by the Boolean object.

valueOf( )

Returns the primitive boolean value contained in the Boolean object.

Description

Boolean values are a fundamental datatype in JavaScript. The Boolean object is an object wrapper around the boolean value. This Boolean object type exists primarily to provide a toString( ) method to convert boolean values to strings. When the toString( ) method is invoked to convert a boolean value to a string (and it is often invoked implicitly by JavaScript), JavaScript internally converts the boolean value to a transient Boolean object, on which the method can be invoked.

See Also

Object


Name

Boolean.toString( ): convert a boolean value to a string — ECMAScript v1: Overrides Object.toString( )

Synopsis

b.toString( )

Returns

The string "true" or "false", depending on the value of the primitive boolean value or Boolean object b.

Throws

TypeError

If this method is invoked on an object that is not a Boolean.


Name

Boolean.valueOf( ): the boolean value of a Boolean object — ECMAScript v1: Overrides Object.valueOf( )

Synopsis

b.valueOf( )

Returns

The primitive boolean value held by the Boolean object b.

Throws

TypeError

If this method is invoked on an object that is not a Boolean.


Name

Date: manipulate dates and times — ECMAScript v1: Object → Date

Constructor

new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year, month, day, hours, minutes, seconds, ms)

With no arguments, the Date( ) constructor creates a Date object set to the current date and time. When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime( ) method. When one string argument is passed, it is a string representation of a date, in the format accepted by the Date.parse( ) method. Otherwise, the constructor is passed between two and seven numeric arguments that specify the individual fields of the date and time. All but the first two arguments—the year and month fields—are optional. Note that these date and time fields are specified using local time, not Coordinated Universal Time (UTC) (which is similar to Greenwich Mean Time [GMT]). See the static Date.UTC( ) method for an alternative.

Date( ) may also be called as a function, without the new operator. When invoked in this way, Date( ) ignores any arguments passed to it and returns a string representation of the current date and time.

Arguments

milliseconds

The number of milliseconds between the desired date and midnight on January 1, 1970 (UTC). For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.

datestring

A single argument that specifies the date and, optionally, the time as a string. The string should be in a format accepted by Date.parse( ).

year

The year, in four-digit format. For example, specify 2001 for the year 2001. For compatibility with early implementations of JavaScript, if this argument is between 0 and 99, 1900 is added to it.

month

The month, specified as an integer from 0 (January) to 11 (December).

day

The day of the month, specified as an integer from 1 to 31. Note that this argument uses 1 as its lowest value, while other arguments use 0 as their lowest value. Optional.

hours

The hour, specified as an integer from 0 (midnight) to 23 (11 p.m.). Optional.

minutes

The minutes in the hour, specified as an integer from 0 to 59. Optional.

seconds

The seconds in the minute, specified as an integer from 0 to 59. Optional.

ms

The milliseconds in the second, specified as an integer from 0 to 999. Optional.

Methods

The Date object has no properties that can be read and written directly; instead, all access to date and time values is done through methods. Most methods of the Date object come in two forms: one that operates using local time and one that operates using universal (UTC or GMT) time. If a method has "UTC" in its name, it operates using universal time. These pairs of methods are listed together below. For example, the listing for get[UTC]Day( ) refers to both the methods getDay( ) and getUTCDay( ).

Date methods may be invoked only on Date objects, and they throw a TypeError exception if you attempt to invoke them on any other type of object:

get[UTC]Date( )

Returns the day of the month of a Date object, in local or universal time.

get[UTC]Day( )

Returns the day of the week of a Date object, in local or universal time.

get[UTC]FullYear( )

Returns the year of the date in full four-digit form, in local or universal time.

get[UTC]Hours( )

Returns the hours field of a Date object, in local or universal time.

get[UTC]Milliseconds( )

Returns the milliseconds field of a Date object, in local or universal time.

get[UTC]Minutes( )

Returns the minutes field of a Date object, in local or universal time.

get[UTC]Month( )

Returns the month field of a Date object, in local or universal time.

get[UTC]Seconds( )

Returns the seconds field of a Date object, in local or universal time.

getTime( )

Returns the internal, millisecond representation of a Date object. Note that this value is independent of time zone, and therefore, there is not a separate getUTCTime( ) method.

getTimezoneOffset( )

Returns the difference, in minutes, between the local and UTC representations of this date. Note that the value returned depends on whether daylight saving time is or would be in effect at the specified date.

getYear( )

Returns the year field of a Date object. Deprecated in favor of getFullYear( ).

set[UTC]Date( )

Sets the day of the month field of the date, using local or universal time.

set[UTC]FullYear( )

Sets the year (and optionally month and day) field of the date, using local or universal time.

set[UTC]Hours( )

Sets the hour field (and optionally the minutes, seconds, and milliseconds fields) of the date, using local or universal time.

set[UTC]Milliseconds( )

Sets the milliseconds field of a date, using local or universal time.

set[UTC]Minutes( )

Sets the minutes field (and optionally the seconds and milliseconds fields) of a date, using local or universal time.

set[UTC]Month( )

Sets the month field (and optionally the day of the month) of a date, using local or universal time.

set[UTC]Seconds( )

Sets the seconds field (and optionally the milliseconds field) of a date, using local or universal time.

setTime( )

Sets the fields of a Date object using the millisecond format.

setYear( )

Sets the year field of a Date object. Deprecated in favor of setFullYear( ).

toDateString( )

Returns a string that represents the date portion of the date, expressed in the local time zone.

toGMTString( )

Converts a Date to a string, using the GMT time zone. Deprecated in favor of toUTCString( ).

toLocaleDateString( )

Returns a string that represents the date portion of the date, expressed in the local time zone, using the local date formatting conventions.

toLocaleString( )

Converts a Date to a string, using the local time zone and the local date formatting conventions.

toLocaleTimeString( )

Returns a string that represents the time portion of the date, expressed in the local time zone, using the local time formatting conventions.

toString( )

Converts a Date to a string using the local time zone.

toTimeString( )

Returns a string that represents the time portion of the date, expressed in the local time zone.

toUTCString( )

Converts a Date to a string, using universal time.

valueOf( )

Converts a Date to its internal millisecond format.

Static Methods

In addition to the many instance methods listed previously, the Date object also defines two static methods. These methods are invoked through the Date( ) constructor itself, not through individual Date objects:

Date.parse( )

Parses a string representation of a date and time and returns the internal millisecond representation of that date.

Date.UTC( )

Returns the millisecond representation of the specified UTC date and time.

Description

The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) syntax shown earlier.

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time. The toString( ) method and its variants convert dates to human-readable strings. getTime( ) and setTime( ) convert to and from the internal representation of the Date object—the number of milliseconds since midnight (GMT) on January 1, 1970. In this standard millisecond format, a date and time are represented by a single integer, which makes date arithmetic particularly easy. The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so the JavaScript clock will not "roll over" until the year 275755.

Examples

Once you create a Date object, there are a variety of methods you can use to operate on it:

d = new Date( );  // Get the current date and time
document.write('Today is: " + d.toLocaleDateString( ) + '. ');  // Display date
document.write('The time is: ' + d.toLocaleTimeString( ));      // Display time
var dayOfWeek = d.getDay( );                                    // What weekday is it?
var weekend = (dayOfWeek == 0) || (dayOfWeek == 6);            // Is it a weekend?

Another common use of the Date object is to subtract the millisecond representations of the current time from some other time to determine the difference between the two times. The following client-side example shows two such uses:

<script language="JavaScript">

today = new Date( );            // Make a note of today's date
christmas = new Date( );        // Get a date with the current year
christmas.setMonth(11);        // Set the month to December...
christmas.setDate(25);         // and the day to the 25th
// If Christmas hasn't already passed, compute the number of
// milliseconds between now and Christmas, convert this
// to a number of days and print a message
if (today.getTime() < christmas.getTime( )) {
    difference = christmas.getTime() - today.getTime( );
    difference = Math.floor(difference / (1000 * 60 * 60 * 24));
    document.write('Only ' + difference + ' days until Christmas!<p>');
}
</script>
// ... rest of HTML document here ...
<script language="JavaScript">
// Here we use Date objects for timing
// We divide by 1000 to convert milliseconds to seconds
now = new Date( );
document.write('<p>It took ' +
    (now.getTime()-today.getTime( ))/1000 +
    'seconds to load this page.');
</script>

See Also

Date.parse( ), Date.UTC( )

Name

Date.getDate( ): return the day-of-the-month field of a Date — ECMAScript v1

Synopsis

date.getDate( )

Returns

The day of the month of the specified Date object date, using local time. Return values are between 1 and 31.


Name

Date.getDay( ): return the day-of-the-week field of a Date — ECMAScript v1

Synopsis

date.getDay( )

Returns

The day of the week of the specified Date object date, using local time. Return values are between 0 (Sunday) and 6 (Saturday).


Name

Date.getFullYear( ): return the year field of a Date — ECMAScript v1

Synopsis

date.getFullYear( )

Returns

The year that results when date is expressed in local time. The return value is a full four-digit year, including the century, not a two-digit abbreviation.


Name

Date.getHours( ): return the hours field of a Date — ECMAScript v1

Synopsis

date.getHours( )

Returns

The hours field, expressed in local time, of the specified Date object date. Return values are between 0 (midnight) and 23 (11 p.m.).


Name

Date.getMilliseconds( ): return the milliseconds field of a Date — ECMAScript v1

Synopsis

date.getMilliseconds( )

Returns

The milliseconds field, expressed in local time, of date.


Name

Date.getMinutes( ): return the minutes field of a Date — ECMAScript v1

Synopsis

date.getMinutes( )

Returns

The minutes field, expressed in local time, of the specified Date object date. Return values are between 0 and 59.


Name

Date.getMonth( ): return the month field of a Date — ECMAScript v1

Synopsis

date.getMonth( )

Returns

The month field, expressed in local time, of the specified Date object date. Return values are between 0 ( January) and 11 (December).


Name

Date.getSeconds( ): return the seconds field of a Date — ECMAScript v1

Synopsis

date.getSeconds( )

Returns

The seconds field, expressed in local time, of the specified Date object date. Return values are between 0 and 59.


Name

Date.getTime( ): return a Date in milliseconds — ECMAScript v1

Synopsis

date.getTime( )

Returns

The millisecond representation of the specified Date object date—that is, the number of milliseconds between midnight (GMT) on 1/1/1970 and the date and time specified by date.

Description

getTime( ) converts a date and time to a single integer. This is useful when you want to compare two Date objects or to determine the time elapsed between two dates. Note that the millisecond representation of a date is independent of the time zone, so there is no getUTCTime( ) method in addition to this one. Don't confuse this getTime( ) method with the getDay( ) and getDate( ) methods, which return the day of the week and the day of the month, respectively.

Date.parse( ) and Date.UTC( ) allow you to convert a date and time specification to a millisecond representation without going through the overhead of first creating a Date object.

See Also

Date, Date.parse( ), Date.setTime( ), Date.UTC( )


Name

Date.getTimezoneOffset( ): determine the offset from GMT — ECMAScript v1

Synopsis

date.getTimezoneOffset( )

Returns

The difference, in minutes, between GMT and local time.

Description

getTimezoneOffset( ) returns the number of minutes difference between the GMT or UTC time and the local time. In effect, this function tells you what time zone the JavaScript code is running in and whether or not daylight saving time is (or would be) in effect at the specified date.

The return value is measured in minutes, rather than hours, because some countries have time zones that are not at even one-hour intervals.


Name

Date.getUTCDate( ): return the day-of-the-month field of a Date (universal time) — ECMAScript v1

Synopsis

date.getUTCDate( )

Returns

The day of the month (a value between 1 and 31) that results when date is expressed in universal time.


Name

Date.getUTCDay( ): return the day-of-the-week field of a Date (universal time) — ECMAScript v1

Synopsis

date.getUTCDay( )

Returns

The day of the week that results when date is expressed in universal time. Return values are between 0 (Sunday) and 6 (Saturday).


Name

Date.getUTCFullYear( ): return the year field of a Date (universal time) — ECMAScript v1

Synopsis

date.getUTCFullYear( )

Returns

The year that results when date is expressed in universal time. The return value is a full four-digit year, not a two-digit abbreviation.


Name

Date.getUTCHours( ): return the hours field of a Date (universal time) — ECMAScript v1

Synopsis

date.getUTCHours( )

Returns

The hours field, expressed in universal time, of date. The return value is an integer between 0 (midnight) and 23 (11 p.m.).


Name

Date.getUTCMilliseconds( ): return the milliseconds field of a Date (universal time) — ECMAScript v1

Synopsis

date.getUTCMilliseconds( )

Returns

The milliseconds field, expressed in universal time, of date.


Name

Date.getUTCMinutes( ): return the minutes field of a Date (universal time) — ECMAScript v1

Synopsis

date.getUTCMinutes( )

Returns

The minutes field, expressed in universal time, of date. The return value is an integer between 0 and 59.


Name

Date.getUTCMonth( ): return the month-of-the-year field of a Date (universal time) — ECMAScript v1

Synopsis

date.getUTCMonth( )

Returns

The month of the year that results when date is expressed in universal time. The return value is an integer between 0 ( January) and 11 (December). Note that the Date object represents the first day of the month as 1 but represents the first month of the year as 0.


Name

Date.getUTCSeconds( ): return the seconds field of a Date (universal time) — ECMAScript v1

Synopsis

date.getUTCSeconds( )

Returns

The seconds field, expressed in universal time, of date. The return value is an integer between 0 and 59.


Name

Date.getYear( ): return the year field of a Date — ECMAScript v1; deprecated by ECMAScript v3

Synopsis

date.getYear( )

Returns

The year field of the specified Date object date minus 1900.

Description

getYear( ) returns the year field of a specified Date object minus 1900. As of ECMAScript v3, it is not required in conforming JavaScript implementations; use getFullYear( ) instead.


Name

Date.parse( ): parse a date/time string — ECMAScript v1

Synopsis

Date.parse(date)

Arguments

date

A string containing the date and time to be parsed.

Returns

The number of milliseconds between the specified date and time and midnight GMT on January 1, 1970.

Description

Date.parse( )is a static method of Date. It is always invoked through the Date constructor as Date.parse( ), not through a Date object as date .parse( ). Date.parse( ) takes a single string argument. It parses the date contained in this string and returns it in millisecond format, which can be used directly, used to create a new Date object, or used to set the date in an existing Date object with Date.setTime( ).

The ECMAScript standard does not specify the format of the strings that can be parsed by Date.parse( ) except to say that this method can parse the strings returned by the Date.toString( ) and Date.toUTCString( ) methods. Unfortunately, these functions format dates in an implementation-dependent way, so it is not, in general, possible to write dates in a way that is guaranteed to be understood by all JavaScript implementations.

See Also

Date, Date.setTime( ), Date.toGMTString( ), Date.UTC( )


Name

Date.setDate( ): set the day-of-the-month field of a Date — ECMAScript v1

Synopsis

date.setDate(day_of_month)

Arguments

day_of_month

An integer between 1 and 31 that is used as the new value (in local time) of the day-of-the-month field of date.

Returns

The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.


Name

Date.setFullYear( ): set the year and, optionally, the month and date fields of a Date — ECMAScript v1

Synopsis

date.setFullYear(year)

date.setFullYear(year, month)

date.setFullYear(year, month, day)

Arguments

year

The year, expressed in local time, to be set in date. This argument should be an integer that includes the century, such as 1999; it should not be an abbreviation, such as 99.

month

An optional integer between 0 and 11 that is used as the new value (in local time) of the month field of date.

day

An optional integer between 1 and 31 that is used as the new value (in local time) of the day-of-the-month field of date.

Returns

The internal millisecond representation of the adjusted date.


Name

Date.setHours( ): set the hours, minutes, seconds, and milliseconds fields of a Date — ECMAScript v1

Synopsis

date.setHours(hours)

date.setHours(hours, minutes)

date.setHours(hours, minutes, seconds)

date.setHours(hours, minutes, seconds, millis)

Arguments

hours

An integer between 0 (midnight) and 23 (11 p.m.) local time that is set as the new hours value of date.

minutes

An optional integer, between 0 and 59, that is used as the new value (in local time) of the minutes field of date. This argument is not supported prior to ECMAScript standardization.

seconds

An optional integer, between 0 and 59, that is used as the new value (in local time) of the seconds field of date. This argument is not supported prior to ECMAScript standardization.

millis

An optional integer, between 0 and 999, that is used as the new value (in local time) of the milliseconds field of date. This argument is not supported prior to ECMAScript standardization.

Returns

The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.


Name

Date.setMilliseconds( ): set the milliseconds field of a Date — ECMAScript v1

Synopsis

date.setMilliseconds(millis)

Arguments

millis

The milliseconds field, expressed in local time, to be set in date. This argument should be an integer between 0 and 999.

Returns

The millisecond representation of the adjusted date.


Name

Date.setMinutes( ): set the minutes, seconds, and milliseconds fields of a Date — ECMAScript v1

Synopsis

date.setMinutes(minutes)

date.setMinutes(minutes, seconds)

date.setMinutes(minutes, seconds, millis)

Arguments

minutes

An integer between 0 and 59 that is set as the minutes value (in local time) of the Date object date.

seconds

An optional integer, between 0 and 59, that is used as the new value (in local time) of the seconds field of date. This argument is not supported prior to ECMAScript standardization.

millis

An optional integer, between 0 and 999, that is used as the new value (in local time) of the milliseconds field of date. This argument is not supported prior to ECMAScript standardization.

Returns

The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.


Name

Date.setMonth( ): set the month and day fields of a Date — ECMAScript v1

Synopsis

date.setMonth(month)

date.setMonth(month, day)

Arguments

month

An integer between 0 ( January) and 11 (December) that is set as the month value (in local time) for the Date object date. Note that months are numbered beginning with 0, while days within the month are numbered beginning with 1.

day

An optional integer between 1 and 31 that is used as the new value (in local time) of the day-of-the-month field of date. This argument is not supported prior to ECMAScript standardization.

Returns

The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.


Name

Date.setSeconds( ): set the seconds and milliseconds fields of a Date — ECMAScript v1

Synopsis

date.setSeconds(seconds)

date.setSeconds(seconds, millis)

Arguments

seconds

An integer between 0 and 59 that is set as the seconds value for the Date object date.

millis

An optional integer, between 0 and 999, that is used as the new value (in local time) of the milliseconds field of date. This argument is not supported prior to ECMAScript standardization.

Returns

The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.


Name

Date.setTime( ): set a Date in milliseconds — ECMAScript v1

Synopsis

date.setTime(milliseconds)

Arguments

milliseconds

The number of milliseconds between the desired date and time and midnight GMT on January 1, 1970. A millisecond value of this type may also be passed to the Date( ) constructor and may be obtained by calling the Date.UTC( ) and Date.parse( ) methods. Representing a date in this millisecond format makes it independent of time zone.

Returns

The milliseconds argument. Prior to ECMAScript standardization, this method returns nothing.


Name

Date.setUTCDate( ): set the day-of-the-month field of a Date (universal time) — ECMAScript v1

Synopsis

date.setUTCDate(day_of_month)

Arguments

day_of_month

The day of the month, expressed in universal time, to be set in date. This argument should be an integer between 1 and 31.

Returns

The internal millisecond representation of the adjusted date.


Name

Date.setUTCFullYear( ): set the year, month, and day fields of a Date (universal time) — ECMAScript v1

Synopsis

date.setUTCFullYear(year)

date.setUTCFullYear(year, month)

date.setUTCFullYear(year, month, day)

Arguments

year

The year, expressed in universal time, to be set in date. This argument should be an integer that includes the century, such as 1999, not an abbreviation, such as 99.

month

An optional integer between 0 and 11 that is used as the new value (in universal time) of the month field of date. Note that months are numbered beginning with 0, while days within the month are numbered beginning with 1.

day

An optional integer between 1 and 31 that is used as the new value (in universal time) of the day-of-the-month field of date.

Returns

The internal millisecond representation of the adjusted date.


Name

Date.setUTCHours( ): set the hours, minutes, seconds, and milliseconds fields of a Date (universal time) — ECMAScript v1

Synopsis

date.setUTCHours(hours)

date.setUTCHours(hours, minutes)

date.setUTCHours(hours, minutes, seconds)

date.setUTCHours(hours, minutes, seconds, millis)

Arguments

hours

The hours field, expressed in universal time, to be set in date. This argument should be an integer between 0 (midnight) and 23 (11 p.m.).

minutes

An optional integer, between 0 and 59, that is used as the new value (in universal time) of the minutes field of date.

seconds

An optional integer, between 0 and 59, that is used as the new value (in universal time) of the seconds field of date.

millis

An optional integer, between 0 and 999, that is used as the new value (in universal time) of the milliseconds field of date.

Returns

The millisecond representation of the adjusted date.


Name

Date.setUTCMilliseconds( ): set the milliseconds field of a Date (universal time) — ECMAScript v1

Synopsis

date.setUTCMilliseconds(millis)

Arguments

millis

The milliseconds field, expressed in universal time, to be set in date. This argument should be an integer between 0 and 999.

Returns

The millisecond representation of the adjusted date.


Name

Date.setUTCMinutes( ): set the minutes, seconds, and milliseconds fields of a Date (universal time) — ECMAScript v1

Synopsis

date.setUTCMinutes(minutes)

date.setUTCMinutes(minutes, seconds)

date.setUTCMinutes(minutes, seconds, millis)

Arguments

minutes

The minutes field, expressed in universal time, to be set in date. This argument should be an integer between 0 and 59.

seconds

An optional integer between 0 and 59 that is used as the new value (in universal time) of the seconds field of date.

millis

An optional integer between 0 and 999 that is used as the new value (in universal time) of the milliseconds field of date.

Returns

The millisecond representation of the adjusted date.


Name

Date.setUTCMonth( ): set the month and day fields of a Date (universal time) — ECMAScript v1

Synopsis

date.setUTCMonth(month)

date.setUTCMonth(month, day)

Arguments

month

The month, expressed in universal time, to be set in date. This argument should be an integer between 0 (January) and 11 (December). Note that months are numbered beginning with 0, while days within the month are numbered beginning with 1.

day

An optional integer between 1 and 31 that is used as the new value (in universal time) of the day-of-the-month field of date.

Returns

The millisecond representation of the adjusted date.


Name

Date.setUTCSeconds( ): set the seconds and milliseconds fields of a Date (universal time) — ECMAScript v1

Synopsis

date.setUTCSeconds(seconds)

date.setUTCSeconds(seconds, millis)

Arguments

seconds

The seconds field, expressed in universal time, to be set in date. This argument should be an integer between 0 and 59.

millis

An optional integer between 0 and 999 that is used as the new value (in universal time) of the milliseconds field of date.

Returns

The millisecond representation of the adjusted date.


Name

Date.setYear( ): set the year field of a Date — ECMAScript v1; deprecated by ECMAScript v3

Synopsis

date.setYear(year)

Arguments

year

An integer that is set as the year value (in local time) for the Date object date. If this value is between 0 and 99, inclusive, 1900 is added to it and it is treated as a year between 1900 and 1999.

Returns

The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.

Description

setYear( ) sets the year field of a specified Date object, with special behavior for years between 1900 and 1999.

As of ECMAScript v3, this function is no longer required in conforming JavaScript implementations; use setFullYear( ) instead.


Name

Date.toDateString( ): return the date portion of a Date as a string — ECMAScript v3

Synopsis

date.toDateString( )

Returns

An implementation-dependent, human-readable string representation of the date portion of date, expressed in the local time zone.

See Also

Date.toLocaleDateString( )
Date.toLocaleString( )
Date.toLocaleTimeString( )
Date.toString( )
Date.toTimeString( )

Name

Date.toGMTString( ): convert a Date to a universal time string — ECMAScript v1; deprecated by ECMAScript v3

Synopsis

date.toGMTString( )

Returns

A string representation of the date and time specified by the Date object date. The date is converted from the local time zone to the GMT time zone before being converted to a string.

Description

toGMTString( ) is deprecated in favor of the identical method Date.toUTCString( ).

As of ECMAScript v3, conforming implementations of JavaScript are no longer required to provide this method; use toUTCString( ) instead.

See Also

Date.toUTCString( )


Name

Date.toLocaleDateString( ): return the date portion of a Date as a locally formatted string — ECMAScript v3

Synopsis

date.toLocaleDateString( )

Returns

An implementation-dependent, human-readable string representation of the date portion of date, expressed in the local time zone and formatted according to local conventions.

See Also

Date.toDateString( ), Date.toLocaleString( ), Date.toLocaleTimeString( ), Date.toString( ), Date.toTimeString( )


Name

Date.toLocaleString( ): convert a Date to a locally formatted string — ECMAScript v1

Synopsis

date.toLocaleString( )

Returns

A string representation of the date and time specified by date. The date and time are represented in the local time zone and formatted using locally appropriate conventions.

Usage

toLocaleString( ) converts a date to a string, using the local time zone. This method also uses local conventions for date and time formatting, so the format may vary from platform to platform and from country to country. toLocaleString( ) returns a string formatted in what is likely the user's preferred date and time format.

See Also

Date.toLocaleDateString( ), Date.toLocaleTimeString( ), Date.toString( ), Date.toUTCString( )


Name

Date.toLocaleTimeString( ): return the time portion of a Date as a locally formatted string — ECMAScript v3

Synopsis

date.toLocaleTimeString( )

Returns

An implementation-dependent, human-readable string representation of the time portion of date, expressed in the local time zone and formatted according to local conventions.

See Also

Date.toDateString( ), Date.toLocaleDateString( ), Date.toLocaleString( ), Date.toString( ), Date.toTimeString( )


Name

Date.toString( ): convert a Date to a string — ECMAScript v1: Overrides Object.toString( )

Synopsis

date.toString( )

Returns

A human-readable string representation of date, expressed in the local time zone.

Description

toString( ) returns a human-readable, implementation-dependent string representation of date. Unlike toUTCString( ), toString( ) expresses the date in the local time zone. Unlike toLocaleString( ), toString( ) may not represent the date and time using locale-specific formatting.

See Also

Date.parse( )
Date.toDateString( )
Date.toLocaleString( )
Date.toTimeString( )
Date.toUTCString( )

Name

Date.toTimeString( ): return the time portion of a Date as a string — ECMAScript v3

Synopsis

date.toTimeString( )

Returns

A implementation-dependent, human-readable string representation of the time portion of date, expressed in the local time zone.

See Also

Date.toString( ), Date.toDateString( ), Date.toLocaleDateString( ), Date.toLocaleString( ), Date.toLocaleTimeString( )


Name

Date.toUTCString( ): convert a Date to a string (universal time) — ECMAScript v1

Synopsis

date.toUTCString( )

Returns

A human-readable string representation, expressed in universal time, of date.

Description

toUTCString( ) returns an implementation-dependent string that represents date in universal time.

See Also

Date.toLocaleString( ), Date.toString( )


Name

Date.UTC( ): convert a Date specification to milliseconds — ECMAScript v1

Synopsis

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

Arguments

year

The year in four-digit format. If this argument is between 0 and 99, inclusive, 1900 is added to it and it is treated as a year between 1900 and 1999.

month

The month, specified as an integer from 0 (January) to 11 (December).

day

The day of the month, specified as an integer from 1 to 31. Note that this argument uses 1 as its lowest value, while other arguments use 0 as their lowest value. This argument is optional.

hours

The hour, specified as an integer from 0 (midnight) to 23 (11 p.m.). This argument is optional.

minutes

The minutes in the hour, specified as an integer from 0 to 59. This argument is optional.

seconds

The seconds in the minute, specified as an integer from 0 to 59. This argument is optional.

ms

The number of milliseconds, specified as an integer from 0 to 999. This argument is optional and is ignored prior to ECMAScript standardization.

Returns

The millisecond representation of the specified universal time. That is, this method returns the number of milliseconds between midnight GMT on January 1, 1970 and the specified time.

Description

Date.UTC( ) is a static method; it is invoked through the Date( ) constructor, not through an individual Date object.

The arguments to Date.UTC( ) specify a date and time and are understood to be in UTC; they are in the GMT time zone. The specified UTC time is converted to the millisecond format, which can be used by the Date( ) constructor method and by the Date.setTime( ) method.

The Date( ) constructor method can accept date and time arguments identical to those that Date.UTC( ) accepts. The difference is that the Date( ) constructor assumes local time, while Date.UTC( ) assumes universal time (GMT). To create a Date object using a UTC time specification, you can use code like this:

d = new Date(Date.UTC(1996, 4, 8, 16, 30));

See Also

Date, Date.parse( ), Date.setTime( )


Name

Date.valueOf( ): convert a Date to millisecond representation — ECMAScript v1: Overrides Object.valueOf( )

Synopsis

date.valueOf( )

Returns

The millisecond representation of date. The value returned is the same as that returned by Date.getTime( ).


Name

decodeURI( ): unescape characters in a URI — ECMAScript v3

Synopsis

decodeURI(uri)

Arguments

uri

A string that contains an encoded URI or other text to be decoded.

Returns

A copy of uri, with any hexadecimal escape sequences replaced with the characters they represent.

Throws

URIError

Indicates that one or more of the escape sequences in uri is malformed and cannot be correctly decoded.

Description

decodeURI( ) is a global function that returns a decoded copy of its uri argument. It reverses the encoding performed by encodeURI( ); see that function's reference page for details.

See Also

decodeURIComponent( ), encodeURI( ), encodeURIComponent( ), escape( ), unescape( )


Name

decodeURIComponent( ): unescape characters in a URI component — ECMAScript v3

Synopsis

decodeURI(s)

Arguments

s

A string that contains an encoded URI component or other text to be decoded.

Returns

A copy of s, with any hexadecimal escape sequences replaced with the characters they represent.

Throws

URIError

Indicates that one or more of the escape sequences in s is malformed and cannot be correctly decoded.

Description

decodeURIComponent( ) is a global function that returns a decoded copy of its s argument. It reverses the encoding performed by encodeURIComponent( ). See that function's reference page for details.

See Also

decodeURI( ), encodeURI( ), encodeURIComponent( ), escape( ), unescape( )


Name

encodeURI( ): escape characters in a URI — ECMAScript v3

Synopsis

encodeURI(uri)

Arguments

uri

A string that contains the URI or other text to be encoded.

Returns

A copy of uri, with certain characters replaced by hexadecimal escape sequences.

Throws

URIError

Indicates that uri contains malformed Unicode surrogate pairs and cannot be encoded.

Description

encodeURI( ) is a global function that returns an encoded copy of its uri argument. ASCII letters and digits are not encoded, nor are the following ASCII punctuation characters:

- _ . ! ~ * ' ( )

Because encodeURI( ) is intended to encode complete URIs, the following ASCII punctuation characters, which have special meaning in URIs, are not escaped either:

; / ? : @ & = + $ , #

Any other characters in uri are replaced by converting each character to its UTF-8 encoding and then encoding each of the resulting one, two, or three bytes with a hexadecimal escape sequence of the form %xx. In this encoding scheme, ASCII characters are replaced with a single %xx escape, characters with encodings between \u0080 and \u07ff are replaced with two escape sequences, and all other 16-bit Unicode characters are replaced with three escape sequences.

If you use this method to encode a URI, you should be certain that none of the components of the URI (such as the query string) contain URI separator characters such as ? and #. If the components have to contain these characters, you should encode each component separately with encodeURIComponent( ).

Use decodeURI( ) to reverse the encoding applied by this method. Prior to ECMAScript v3, you can use escape( ) and unescape( ) methods (which are now deprecated) to perform a similar kind of encoding and decoding.

Example

// Returns http://www.isp.com/app.cgi?arg1=1&arg2=hello%20world
encodeURI("http://www.isp.com/app.cgi?arg1=1&arg2=hello world");
encodeURI("\u00a9");  // The copyright character encodes to %C2%A9

See Also

decodeURI( ), decodeURIComponent( ), encodeURIComponent( ), escape( ), unescape( )


Name

encodeURIComponent( ): escape characters in a URI component — ECMAScript v3

Synopsis

encodeURIComponent(s)

Arguments

s

A string that contains a portion of a URI or other text to be encoded.

Returns

A copy of s, with certain characters replaced by hexadecimal escape sequences.

Throws

URIError

Indicates that s contains malformed Unicode surrogate pairs and cannot be encoded.

Description

encodeURIComponent( ) is a global function that returns an encoded copy of its s argument. ASCII letters and digits are not encoded, nor are the following ASCII punctuation characters:

- _ . ! ~ * ' ( )

All other characters, including punctuation characters such as /, :, and # that serve to separate the various components of a URI, are replaced with one or more hexadecimal escape sequences. See encodeURI( ) for a description of the encoding scheme used.

Note the difference between encodeURIComponent( ) and encodeURI( ): encodeURIComponent( ) assumes that its argument is a portion (such as the protocol, hostname, path, or query string) of a URI. Therefore it escapes the punctuation characters that are used to separate the portions of a URI.

Example

encodeURIComponent("hello world?");  // Returns hello%20world%3F

See Also

decodeURI( ), decodeURIComponent( ), encodeURI( ), escape( ), unescape( )


Name

Error: a generic exception — ECMAScript v3: Object → Error

Constructor

new Error( )

new Error(message)

Arguments

message

An optional error message that provides details about the exception.

Returns

A newly constructed Error object. If the message argument is specified, the Error object uses it as the value of its message property; otherwise, it uses an implementation-defined default string as the value of that property. When the Error( ) constructor is called as a function, without the new operator, it behaves just as it does when called with the new operator.

Properties

message

An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string.

name

A string that specifies the type of the exception. For instances of the Error class and all of its subclasses, this property specifies the name of the constructor used to create the instance.

Methods

toString( )

Returns an implementation-defined string that represents this Error object.

Description

Instances of the Error class represent errors or exceptions and are typically used with the throw and try/catch statements. The name property specifies the type of the exception, and the message property can provide human-readable details about the exception.

The JavaScript interpreter never throws Error objects directly; instead, it throws instances of one of the Error subclasses, such as SyntaxError or RangeError. In your own code, you may find it convenient to throw Error objects to signal exceptions, or you may prefer to simply throw an error message or error code as a primitive string or number value.

Note that the ECMAScript specification defines a toString( ) method for the Error class (it is inherited by each of the subclasses of Error) but that it does not require this toString( ) method to return a string that contains the contents of the message property. Therefore, you should not expect the toString( ) method to convert an Error object to a meaningful, human-readable string. To display an error message to a user, you should explicitly use the name and message properties of the Error object.

Examples

You might signal an exception with code like the following:

function factorial(x) {
    if (x < 0) throw new Error("factorial: x must be >= 0");
    if (x <= 1) return 1; else return x * factorial(x-1);
}

And if you catch an exception, you might display its to the user with code like the following (which uses the client-side Window.alert( ) method):

try { &*(&/* an error is thrown here */ }
catch(e) {
    if (e instanceof Error) {  // Is it an instance of Error or a subclass?
        alert(e.name + ": " + e.message);
    }
}

See Also

EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError


Name

Error.message: a human-readable error message — ECMAScript v3

Synopsis

error.message

Description

The message property of an Error object (or of an instance of any subclass of Error) is intended to contain a human-readable string that provides details about the error or exception that occurred. If a message argument is passed to the Error( ) constructor, this message becomes the value of the message property. If no message argument is passed, an Error object inherits an implementation-defined default value (which may be the empty string) for this property.


Name

Error.name: the type of an error — ECMAScript v3

Synopsis

error.name

Description

The name property of an Error object (or of an instance of any subclass of Error) specifies the type of error or exception that occurred. All Error objects inherit this property from their constructor. The value of the property is the same as the name of the constructor. Thus SyntaxError objects have a name property of "SyntaxError", and EvalError objects have a name of "EvalError".


Name

Error.toString( ): convert an Error object to a string — ECMAScript v3: Overrides Object.toString( )

Synopsis

error. toString( )

Returns

An implementation-defined string. The ECMAScript standard does not specify anything about the return value of this method, except that it is a string. Notably, it does not require the returned string to contain the error name or the error message.


Name

escape( ): encode a string — ECMAScript v1; deprecated in ECMAScript v3

Synopsis

escape(s)

Arguments

s

The string that is to be "escaped" or encoded.

Returns

An encoded copy of s in which certain characters have been replaced by hexadecimal escape sequences.

Description

escape( ) is a global function. It returns a new string that contains an encoded version of s. The string s itself is not modified.

escape( ) returns a string in which all characters of s other than ASCII letters, digits, and the punctuation characters @, *, _, +, -, ., and / have been replaced by escape sequences of the form % xx or %u xxxx (where x represents a hexadecimal digit). Unicode characters \u0000 to \u00ff are replaced with the % xx escape sequence, and all other Unicode characters are replaced with the %u xxxx sequence.

Use the unescape( ) function to decode a string encoded with escape( ).

Although the escape( ) function was standardized in the first version of ECMAScript, it was deprecated and removed from the standard by ECMAScript v3. Implementations of ECMAScript are likely to implement this function, but they are not required to. You should use encodeURI( ) and encodeURIComponent( ) instead of escape( ).

Example

escape("Hello World!");  // Returns "Hello%20World%21"

See Also

encodeURI( ), encodeURIComponent( )


Name

eval( ): execute JavaScript code from a string — ECMAScript v1

Synopsis

eval(code)

Arguments

code

A string that contains the JavaScript expression to be evaluated or the statements to be executed.

Returns

The value of the evaluated code, if any.

Throws

SyntaxError

Indicates that code does not contain legal JavaScript.

EvalError

Indicates that eval( ) was called illegally, through an identifier other than "eval", for example. See the restrictions on this function described in the next section.

Other exception

If the JavaScript code passed to eval( ) generates an exception, eval( ) passes that exception on to the caller.

Description

eval( ) is a global method that evaluates a string of JavaScript code in the current lexical scope. If code contains an expression, eval evaluates the expression and returns its value. If code contains a JavaScript statement or statements, eval( ) executes those statements and returns the value, if any, returned by the last statement. If code does not return any value, eval( ) returns undefined. Finally, if code throws an exception, eval( ) passes that exception on to the caller.

eval( ) provides a very powerful capability to the JavaScript language, but its use is infrequent in real-world programs. Obvious uses are to write programs that act as recursive JavaScript interpreters and to write programs that dynamically generate and evaluate JavaScript code.

Most JavaScript functions and methods that expect string arguments accept arguments of other types as well and simply convert those argument values to strings before proceeding. eval( ) does not behave like this. If the code argument is not a primitive string, it is simply returned unchanged. Be careful, therefore, that you do not inadvertently pass a String object to eval( ) when you intended to pass a primitive string value.

For purposes of implementation efficiency, the ECMAScript v3 standard places an unusual restriction on the use of eval( ). An ECMAScript implementation is allowed to throw an EvalError exception if you attempt to overwrite the eval property or if you assign the eval( ) method to another property and attempt to invoke it through that property.

Example

eval("1+2");        // Returns 3
// This code uses client-side JavaScript methods to prompt the user to
// enter an expression and to display the results of evaluating it.
// See the client-side methods Window.alert() and Window.prompt( ) for details.
try {
    alert("Result: " +  eval(prompt("Enter an expression:","")));
}
catch(exception) {
    alert(exception);
}
var myeval = eval;  // May throw an EvalError
myeval("1+2");      // May throw an EvalError

Name

EvalError: thrown when eval( ) is used improperly — ECMAScript v3: Object → Error → EvalError

Constructor

new EvalError( )

new EvalError(message)

Arguments

message

An optional error message that provides details about the exception. If specified, this argument is used as the value for the message property of the EvalError object.

Returns

A newly constructed EvalError object. If the message argument is specified, the Error object uses it as the value of its message property; otherwise, it uses an implementation-defined default string as the value of that property. When the EvalError( ) constructor is called as a function without the new operator, it behaves just as it does when called with the new operator.

Properties

message

An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string. See Error.message for details.

name

A string that specifies the type of the exception. All EvalError objects inherit the value "EvalError" for this property.

Description

An instance of the EvalError class may be thrown when the global function eval( ) is invoked under any other name. See eval( ) for an explanation of the restrictions on how this function may be invoked. See Error for details about throwing and catching exceptions.

See Also

Error, Error.message, Error.name


Name

Function: a JavaScript function — ECMAScript v1: Object → Function

Synopsis

functionfunctionname(argument_name_list) // Function definition statement
{
    body}
function (argument_name_list) {body}      // Unnamed function literal

functionname(argument_value_list)         // Function invocation

Constructor

new Function(argument_names..., body)

Arguments

argument_names...

Any number of string arguments, each naming one or more arguments of the Function object being created.

body

A string that specifies the body of the function. It may contain any number of JavaScript statements, separated with semicolons, and may refer to any of the argument names specified by previous arguments to the constructor.

Returns

A newly created Function object. Invoking the function executes the JavaScript code specified by body.

Throws

SyntaxError

Indicates that there was a JavaScript syntax error in the body argument or in one of the argument_names arguments.

Properties

arguments[]

An array of arguments that were passed to the function. Deprecated.

caller

A reference to the Function object that invoked this one, or null if the function was invoked from top-level code. Deprecated.

length

The number of named arguments specified when the function was declared.

prototype

An object which, for a constructor function, defines properties and methods shared by all objects created with that constructor function.

Methods

apply( )

Invokes a function as a method of a specified object, passing a specified array of arguments.

call( )

Invokes a function as a method of a specified object, passing the specified arguments.

toString( )

Returns a string representation of the function.

Description

A function is a fundamental datatype in JavaScript. Chapter 8, Functions explains how to define and use functions, and Chapter 9, Classes, Constructors, and Prototypes covers the related topics of methods, constructors, and the prototype property of functions. See those chapters for complete details. Note that although function objects may be created with the Function( ) constructor described here, this is not efficient, and the preferred way to define functions, in most cases, is with a function definition statement or a function literal.

In JavaScript 1.1 and later, the body of a function is automatically given a local variable, named arguments, that refers to an Arguments object. This object is an array of the values passed as arguments to the function. Don't confuse this with the deprecated arguments[] property listed earlier. See the Arguments reference page for details.


Name

Function.apply( ): invoke a function as a method of an object — ECMAScript v3

Synopsis

function.apply(thisobj, args)

Arguments

thisobj

The object to which function is to be applied. In the body of the function, thisobj becomes the value of the this keyword. If this argument is null, the global object is used.

args

An array of values to be passed as arguments to function.

Returns

Whatever value is returned by the invocation of function.

Throws

TypeError

If this method is invoked on an object that is not a function or if this method is invoked with an args argument that is not an array or an Arguments object.

Description

apply( ) invokes the specified function as if it were a method of thisobj, passing it the arguments contained in the args array. It returns the value returned by the function invocation. Within the body of the function, the this keyword refers to the thisobj object.

The args argument must be an array or an Arguments object. Use Function.call( ) instead if you want to specify the arguments to pass to the function individually instead of as array elements.

Example

// Apply the default Object.toString( ) method to an object that
// overrides it with its own version of the method. Note no arguments.
Object.prototype.toString.apply(o);
// Invoke the Math.max( ) method with apply to find the largest
// element in an array. Note that first argument doesn't matter
// in this case.
var data = [1,2,3,4,5,6,7,8];
Math.max.apply(null, data);

See Also

Function.call( )

Name

Function.arguments[]: arguments passed to a function — ECMAScript v1; deprecated by ECMAScript v3

Synopsis

function.arguments[i]

function.arguments.length

Description

The arguments property of a Function object is an array of the arguments that are passed to a function. It is defined only while the function is executing. arguments.length specifies the number of elements in the array.

This property is deprecated in favor of the Arguments object. Although ECMAScript v1 supports the Function.arguments property, it has been removed from ECMAScript v3 and conforming implementations may no longer support this property. Therefore, it should never be used in new JavaScript code.

See Also

Arguments

Name

Function.call( ): invoke a function as a method of an object — ECMAScript v3

Synopsis

function.call(thisobj, args...)

Arguments

thisobj

The object on which function is to be invoked. In the body of the function, thisobj becomes the value of the this keyword. If this argument is null, the global object is used.

args...

Any number of arguments, which will be passed as arguments to function.

Returns

Whatever value is returned by the invocation of function.

Throws

TypeError

If this method is invoked on an object that is not a function.

Description

call( ) invokes the specified function as if it were a method of thisobj, passing it any arguments that follow thisobj in the argument list. The return value of call( ) is the value returned by the function invocation. Within the body of the function, the this keyword refers to the thisobj object, or to the global object if thisobj is null.

Use Function.apply( ) instead if you want to specify the arguments to pass to the function in an array.

Example

// Call the default Object.toString( ) method on an object that
// overrides it with its own version of the method. Note no arguments.
Object.prototype.toString.call(o);

See Also

Function.apply( )

Name

Function.caller: the function that called this one — JavaScript 1.0; deprecated by ECMAScript

Synopsis

function.caller

Description

In early versions of JavaScript, the caller property of a Function object is a reference to the function that invoked the current one. If the function is invoked from the top level of a JavaScript program, caller is null. This property may be used only from within the function (i.e., the caller property is only defined for a function while that function is executing).

Function.caller is not part of the ECMAScript standard and is not required in conforming implementations. It should not be used.


Name

Function.length: the number of declared arguments — ECMAScript v1

Synopsis

function.length

Description

The length property of a function specifies the number of named arguments declared when the function was defined. The function may actually be invoked with more than or fewer than this number of arguments. Don't confuse this property of a Function object with the length property of the Arguments object, which specifies the number of arguments actually passed to the function. See Arguments.length for an example.

See Also

Arguments.length

Name

Function.prototype: the prototype for a class of objects — ECMAScript v1

Synopsis

function.prototype

Description

The prototype property is used when a function is used as a constructor. It refers to an object that serves as the prototype for an entire class of objects. Any object created by the constructor inherits all properties of the object referred to by the prototype property.

See Chapter 9, Classes, Constructors, and Prototypes for a full discussion of constructor functions, the prototype property, and the definition of classes in JavaScript.


Name

Function.toString( ): convert a function to a string — ECMAScript v1

Synopsis

function.toString( )

Returns

A string that represents the function.

Throws

TypeError

If this method is invoked on an object that is not a Function.

Description

The toString( ) method of the Function object converts a function to a string in an implementation-dependent way. In most implementations, such as the implementations in Firefox and IE, this method returns a string of valid JavaScript code—code that includes the function keyword, argument list, the complete body of the function, and so on. In these implementations, the output of this toString( ) method is valid input for the global eval( ) function. This behavior is not required by the specification, however, and should not be relied upon.


Name

getClass( ): return the JavaClass of a JavaObject — LiveConnect

Synopsis

getClass(javaobj)

Arguments

javaobj

A JavaObject object.

Returns

The JavaClass object of javaobj.

Description

getClass( ) is a function that takes a JavaObject object (javaobj) as an argument. It returns the JavaClass object of that JavaObject. That is, it returns the JavaClass object that represents the Java class of the Java object represented by the specified JavaObject.

Usage

Don't confuse the JavaScript getClass( ) function with the getClass method of all Java objects. Similarly, don't confuse the JavaScript JavaClass object with the Java java.lang.Class class.

Consider the Java Rectangle object created with the following line:

var r = new java.awt.Rectangle( );

r is a JavaScript variable that holds a JavaObject object. Calling the JavaScript function getClass( ) returns a JavaClass object that represents the java.awt.Rectangle class:

var c = getClass(r);

You can see this by comparing this JavaClass object to java.awt.Rectangle:

if (c == java.awt.Rectangle) ...

The Java getClass( ) method is invoked differently and performs an entirely different function:

c = r.getClass( );

After executing this line of code, c is a JavaObject that represents a java.lang.Class object. This java.lang.Class object is a Java object that is a Java representation of the java.awt.Rectangle class. See your Java documentation for details on what you can do with the java.lang.Class class.

To summarize, you can see that the following expression always evaluates to true for any JavaObject o:

(getClass(o.getClass( )) == java.lang.Class)

See Also

JavaArray, JavaClass, JavaObject, JavaPackage; Chapter 12, Scripting Java, Chapter 23, Scripting Java Applets and Flash Movies


Name

Global: the global object — ECMAScript v1: Object → Global

Synopsis

this

Global Properties

The global object is not a class, so the following global properties have individual reference entries under their own names. That is, you can find details on the undefined property listed under the name undefined, not under Global.undefined. Note that all top-level variables are also properties of the global object:

Infinity

A numeric value that represents positive infinity.

java

A JavaPackage that represents the java.* package hierarchy

NaN

The not-a-number value.

Packages

The root JavaPackage object.

undefined

The undefined value.

Global Functions

The global object is an object, not a class. The global functions listed here are not methods of any object, and their reference entries appear under the function name. For example, you'll find details on the parseInt( ) function under parseInt( ), not Global.parseInt( ):

decodeURI( )

Decodes a string escaped with encodeURI( ).

decodeURIComponent( )

Decodes a string escaped with encodeURIComponent( ).

encodeURI

Encodes a URI by escaping certain characters.

encodeURIComponent

Encodes a URI component by escaping certain characters.

escape( )

Encodes a string by replacing certain characters with escape sequences.

eval( )

Evaluates a string of JavaScript code and returns the result.

getClass( )

Returns the JavaClass of a JavaObject

isFinite( )

Tests whether a value is a finite number.

isNaN( )

Tests whether a value is the not-a-number value.

parseFloat( )

Parses a number from a string.

parseInt( )

Parses an integer from a string.

unescape( )

Decodes a string encoded with escape( ).

Global Objects

In addition to the global properties and functions listed earlier, the global object also defines properties that refer to all the other predefined JavaScript objects. All these properties are constructor functions that define classes except for Math, which is a reference to an object that is not a constructor:

Array

The Array( ) constructor.

Boolean

The Boolean( ) constructor.

Date

The Date( ) constructor.

Error

The Error( ) constructor.

EvalError

The EvalError( ) constructor.

Function

The Function( ) constructor.

Math

A reference to an object that defines mathematical functions.

Number

The Number( ) constructor.

Object

The Object( ) constructor.

RangeError

The RangeError( ) constructor.

ReferenceError

The ReferenceError( ) constructor.

RegExp

The RegExp( ) constructor.

String

The String( ) constructor.

SyntaxError

The SyntaxError( ) constructor.

TypeError

The TypeError( ) constructor.

URIError

The URIError( ) constructor.

Description

The global object is a predefined object that serves as a placeholder for the global properties and functions of JavaScript. All other predefined objects, functions, and properties are accessible through the global object. The global object is not a property of any other object, so it does not have a name. (The title of this reference page was chosen simply for organizational convenience and does not indicate that the global object is named "Global"). In top-level JavaScript code, you can refer to the global object with the keyword this. It is rarely necessary to refer to the global object in this way, however, because the global object serves as the top of the scope chain, which means that unqualified variable and function names are looked up as properties of the object. When JavaScript code refers to the parseInt( ) function, for example, it is referring to the parseInt property of the global object. The fact that the global object is the top of the scope chain also means that all variables declared in top-level JavaScript code become properties of the global object.

The global object is simply an object, not a class. There is no Global( ) constructor, and there is no way to instantiate a new global object.

When JavaScript is embedded in a particular environment, the global object is usually given additional properties that are specific to that environment. In fact, the type of the global object is not specified by the ECMAScript standard, and an implementation or embedding of JavaScript may use an object of any type as the global object, as long as the object defines the basic properties and functions listed here. For example, in JavaScript implementations that allow the scripting of Java via LiveConnect or related technologies, the global object is given the java and Packages properties and the getClass( ) method listed here. And in client-side JavaScript, the global object is a Window object and represents the web browser window within which the JavaScript code is running.

Example

In core JavaScript, none of the predefined properties of the global object are enumerable, so you can list all implicitly and explicitly declared global variables with a for/in loop like this:

var variables = ""
for(var name in this)
    variables += name + "\n";

Name

Infinity: a numeric property that represents infinity — ECMAScript v1

Synopsis

Infinity

Description

Infinity is a global property that contains the special numeric value representing positive infinity. The Infinity property is not enumerated by for/in loops and cannot be deleted with the delete operator. Note that Infinity is not a constant and can be set to any other value, something that you should take care not to do. (Number.POSITIVE_INFINITY is a constant, however.)

See Also

isFinite( ), NaN, Number.POSITIVE_INFINITY


Name

isFinite( ): determine whether a number is finite — ECMAScript v1

Synopsis

isFinite(n)

Arguments

n

The number to be tested.

Returns

true if n is (or can be converted to) a finite number, or false if n is NaN (not a number) or positive or negative infinity.

See Also

Infinity, isNaN( ), NaN, Number.NaN, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY


Name

isNaN( ): check for not-a-number — ECMAScript v1

Synopsis

isNaN(x)

Arguments

x

The value to be tested.

Returns

true if x is (or can be converted to) the special not-a-number value; false if x is any other value.

Description

isNaN( ) tests its argument to determine whether it is the value NaN, which represents an illegal number (such as the result of division by zero). This function is required because comparing a NaN with any value, including itself, always returns false, so it is not possible to test for NaN with the == or === operators.

A common use of isNaN( ) is to test the results of parseFloat( ) and parseInt( ) to determine if they represent legal numbers. You can also use isNaN( ) to check for arithmetic errors, such as division by zero.

Example

isNaN(0);                  // Returns false
isNaN(0/0);                // Returns true
isNaN(parseInt("3"));      // Returns false
isNaN(parseInt("hello"));  // Returns true
isNaN("3");                // Returns false
isNaN("hello");            // Returns true
isNaN(true);               // Returns false
isNaN(undefined);          // Returns true

See Also

isFinite( ), NaN, Number.NaN, parseFloat( ), parseInt( )


Name

java: the JavaPackage for the java.* package hierarchy — LiveConnect

Synopsis

java

Description

In JavaScript implementations that include LiveConnect or other technology for scripting Java, the global java property is a JavaPackage object that represents the java.* package hierarchy. The existence of this property means that a JavaScript expression such as java.util refers to the Java package java.util. For Java packages that do not fall in the java.* hierarchy, see the global Packages property.

See Also

JavaPackage, Packages; Chapter 12, Scripting Java


Name

JavaArray: JavaScript representation of a Java array — LiveConnect

Synopsis

javaarray.length // The length of the array

javaarray[index] // Read or write an array element

Properties

length

A read-only integer that specifies the number of elements in the Java array represented by the JavaArray object.

Description

The JavaArray object is a JavaScript representation of a Java array that allows JavaScript code to read and write the elements of the array using familiar JavaScript array syntax. In addition, the JavaArray object has a length field that specifies the number of elements in the Java array.

When reading and writing values from array elements, data conversion between JavaScript and Java representations is automatically handled by the system. See Chapter 12, Scripting Java for full details.

Usage

Note that Java arrays differ from JavaScript arrays in a couple of important aspects. First, Java arrays have a fixed length that is specified when they are created. For this reason, the JavaArray length field is read-only. The second difference is that Java arrays are typed (i.e., their elements must all be of the same type of data). Attempting to set an array element to a value of the wrong type results in a JavaScript error or exception.

Example

java.awt.Polygon is a JavaClass object. You can create a JavaObject representing an instance of the class like this:

p = new java.awt.Polygon( );

The object p has properties xpoints and ypoints, which are JavaArray objects representing Java arrays of integers. You can initialize the contents of these arrays with JavaScript code like the following:

for(var i = 0; i < p.xpoints.length; i++)
    p.xpoints[i] = Math.round(Math.random( )*100);
for(var i = 0; i < p.ypoints.length; i++)
    p.ypoints[i] = Math.round(Math.random( )*100);

See Also

getClass( ), JavaClass, JavaObject, JavaPackage; Chapter 12, Scripting Java


Name

JavaClass: JavaScript representation of a Java class — LiveConnect

Synopsis

javaclass.static_member   // Read or write a static Java field or method
new javaclass(...)        // Create a new Java object

Properties

Each JavaClass object contains properties that have the same names as the public static fields and methods of the Java class it represents. These properties allow you to read and write the static fields of the class and invoke the static methods of the class. Each JavaClass object has different properties; you can use a for/in loop to enumerate them for any given JavaClass object.

Description

The JavaClass object is a JavaScript representation of a Java class. The properties of a JavaClass object represent the public static fields and methods (sometimes called class fields and class methods) of the represented class. Note that the JavaClass object does not have properties representing the instance fields of a Java class; individual instances of a Java class are represented by the JavaObject object.

The JavaClass object implements the LiveConnect functionality that allows JavaScript programs to read and write the static variables of Java classes using normal JavaScript syntax. It also provides the functionality that allows JavaScript to invoke the static methods of a Java class.

In addition to allowing JavaScript to read and write Java variable and method values, the JavaClass object allows JavaScript programs to create Java objects (represented by a JavaObject object) by using the new keyword and invoking the constructor method of a JavaClass.

The data conversion required for communication between JavaScript and Java through the JavaClass object is handled automatically by LiveConnect. See Chapter 12, Scripting Java for full details.

Usage

Bear in mind that Java is a typed language. This means that each of the fields of an object has a specific datatype that is set to values of only that type. Attempting to set a field to a value that is not of the correct type results in a JavaScript error or exception. Attempting to invoke a method with arguments of the wrong type also causes an error or exception.

Example

java.lang.System is a JavaClass object that represents the java.lang.System class in Java. You can read a static field of this class with code like the following:

var java_console = java.lang.System.out;

You can invoke a static method of this class with a line like this one:

var version = java.lang.System.getProperty("java.version");

Finally, the JavaClass object also allows you to create new Java objects:

var java_date = new java.lang.Date( );

See Also

getClass( ), JavaArray, JavaObject, JavaPackage; Chapter 12, Scripting Java


Name

JavaObject: JavaScript representation of a Java object — LiveConnect

Synopsis

javaobject.member // Read or write an instance field or method

Properties

Each JavaObject object contains properties that have the same names as the public instance fields and methods (but not the static or class fields and methods) of the Java object it represents. These properties allow you to read and write the value of public fields and invoke the public methods. The properties of a given JavaObject object obviously depend on the type of Java object it represents. You can use the for/in loop to enumerate the properties of any given JavaObject.

Description

The JavaObject object is a JavaScript representation of a Java object. The properties of a JavaObject object represent the public instance fields and public instance methods defined for the Java object. (The class or static fields and methods of the object are represented by the JavaClass object.)

The JavaObject object implements the LiveConnect functionality that allows JavaScript programs to read and write the public instance fields of a Java object using normal JavaScript syntax. It also provides the functionality that allows JavaScript to invoke the methods of a Java object. Data conversion between JavaScript and Java representations is handled automatically by LiveConnect. See Chapter 12, Scripting Java for full details.

Usage

Bear in mind that Java is a typed language. This means that each field of an object has a specific datatype, and you can set it only to values of that type. For example, the width field of a java.awt.Rectangle object is an integer field, and attempting to set it to a string causes a JavaScript error or exception.

Example

java.awt.Rectangle is a JavaClass that represents the java.awt.Rectangle class. You can create a JavaObject that represents an instance of this class like this:

var r = new java.awt.Rectangle(0,0,4,5);

You can then read the public instance variables of this JavaObject r with code like this:

var perimeter = 2*r.width + 2*r.height;

You can also set the value of public instance variables of r using JavaScript syntax:

r.width = perimeter/4;
r.height = perimeter/4;

See Also

getClass( ), JavaArray, JavaClass, JavaPackage; Chapter 12, Scripting Java


Name

JavaPackage: JavaScript representation of a Java package — LiveConnect

Synopsis

package.package_name  // Refers to another JavaPackage

package.class_name    // Refers to a JavaClass object

Properties

The properties of a JavaPackage object are the names of the JavaPackage objects and JavaClass objects that it contains. These properties are different for each individual JavaPackage. Note that it is not possible to use the JavaScript for/in loop to iterate over the list of property names of a Package object. Consult a Java reference manual to determine the packages and classes contained within any given package.

Description

The JavaPackage object is a JavaScript representation of a Java package. A package in Java is a collection of related classes. In JavaScript, a JavaPackage can contain classes (represented by the JavaClass object) and other JavaPackage objects.

The global object has a JavaPackage property named java that represents the java.* package hierarchy. This JavaPackage object defines properties that refer to other JavaPackage objects. For example, java.lang and java.net refer to the java.lang and http://java.net packages. The java.awt JavaPackage contains properties named Frame and Button, which are references to JavaClass objects and represent the classes java.awt.Frame and java.awt.Button.

The global object also defines a property named Packages, which is the root JavaPackage whose properties refer to the roots of all known package hierarchies. For example, the expression Packages.javax.swing refers to the Java package javax.swing.

It is not possible to use the for/in loop to determine the names of the packages and classes contained within a JavaPackage. You must have this information in advance. You can find it in any Java reference manual or by examining the Java class hierarchy.

See Chapter 12, Scripting Java for further details on working with Java packages, classes, and objects.

See Also

java, JavaArray, JavaClass, JavaObject, Packages; Chapter 12, Scripting Java


Name

JSObject: see JSObject in Part IV


Name

Math: mathematical functions and constants — ECMAScript v1

Synopsis

Math.constantMath.function( )

Constants

Math.E

The constant e, the base of the natural logarithm.

Math.LN10

The natural logarithm of 10.

Math.LN2

The natural logarithm of 2.

Math.LOG10E

The base-10 logarithm of e.

Math.LOG2E

The base-2 logarithm of e.

Math.PI

The constant π.

Math.SQRT1_2

The number 1 divided by the square root of 2.

Math.SQRT2

The square root of 2.

Static Functions

Math.abs( )

Computes an absolute value.

Math.acos( )

Computes an arccosine.

Math.asin( )

Computes an arcsine.

Math.atan( )

Computes an arctangent.

Math.atan2( )

Computes the angle from the X axis to a point.

Math.ceil( )

Rounds a number up.

Math.cos( )

Computes a cosine.

Math.exp( )

Computes a power of e.

Math.floor( )

Rounds a number down.

Math.log( )

Computes a natural logarithm.

Math.max( )

Returns the larger of two numbers.

Math.min( )

Returns the smaller of two numbers.

Math.pow( )

Computes x y

Math.random( )

Computes a random number.

Math.round( )

Rounds to the nearest integer.

Math.sin( )

Computes a sine.

Math.sqrt( )

Computes a square root.

Math.tan( )

Computes a tangent.

Description

Math is an object that defines properties that refer to useful mathematical functions and constants. These functions and constants are invoked with syntax like this:

y = Math.sin(x);
area = radius * radius * Math.PI;

Math is not a class of objects as Date and String are. There is no Math( ) constructor, and functions like Math.sin( ) are simply functions, not methods that operate on an object.

See Also

Number

Name

Math.abs( ): compute an absolute value — ECMAScript v1

Synopsis

Math.abs(x)

Arguments

x

Any number.

Returns

The absolute value of x.


Name

Math.acos( ): compute an arccosine — ECMAScript v1

Synopsis

Math.acos(x)

Arguments

x

A number between −1.0 and 1.0.

Returns

The arccosine, or inverse cosine, of the specified value x. This return value is between 0 and π radians.


Name

Math.asin( ): compute an arcsine — ECMAScript v1

Synopsis

Math.asin(x)

Arguments

x

A number between −1.0 and 1.0.

Returns

The arcsine of the specified value x. This return value is between -π/2 and π/2 radians.


Name

Math.atan( ): compute an arctangent — ECMAScript v1

Synopsis

Math.atan(x)

Arguments

x

Any number.

Returns

The arc tangent of the specified value x. This return value is between -π/2 and π/2 radians.


Name

Math.atan2( ): compute the angle from the X axis to a point — ECMAScript v1

Synopsis

Math.atan2(y, x)

Arguments

y

The Y coordinate of the point.

x

The X coordinate of the point.

Returns

A value between -π and π radians that specifies the counterclockwise angle between the positive X axis and the point (x, y).

Description

The Math.atan2( ) function computes the arc tangent of the ratio y/x. The y argument can be considered the Y coordinate (or "rise") of a point, and the x argument can be considered the X coordinate (or "run") of the point. Note the unusual order of the arguments to this function: the Y coordinate is passed before the X coordinate.


Name

Math.ceil( ): round a number up — ECMAScript v1

Synopsis

Math.ceil(x)

Arguments

x

Any numeric value or expression.

Returns

The closest integer greater than or equal to x.

Description

Math.ceil( ) computes the ceiling function—i.e., it returns the closest integer value that is greater than or equal to the function argument. Math.ceil( ) differs from Math.round( ) in that it always rounds up, rather than rounding up or down to the closest integer. Also note that Math.ceil( ) does not round negative numbers to larger negative numbers; it rounds them up toward zero.

Example

a = Math.ceil(1.99);   // Result is 2.0
b = Math.ceil(1.01);   // Result is 2.0
c = Math.ceil(1.0);    // Result is 1.0
d = Math.ceil(-1.99);  // Result is -1.0

Name

Math.cos( ): compute a cosine — ECMAScript v1

Synopsis

Math.cos(x)

Arguments

x

An angle, measured in radians. To convert degrees to radians, multiply the degree value by 0.017453293 (2π/360).

Returns

The cosine of the specified value x. This return value is between −1.0 and 1.0.


Name

Math.E: the mathematical constant 'e' — ECMAScript v1

Synopsis

Math.E

Description

Math.E is the mathematical constant e, the base of the natural logarithm, with a value of approximately 2.71828.


Name

Math.exp( ): compute 'e'x — ECMAScript v1

Synopsis

Math.exp(x)

Arguments

x

A numeric value or expression to be used as the exponent.

Returns

e x , e raised to the power of the specified exponent x, where e is the base of the natural logarithm, with a value of approximately 2.71828.


Name

Math.floor( ): round a number down — ECMAScript v1

Synopsis

Math.floor(x)

Arguments

x

Any numeric value or expression.

Returns

The closest integer less than or equal to x.

Description

Math.floor( ) computes the floor function; in other words, it returns the nearest integer value that is less than or equal to the function argument.

Math.floor( ) rounds a floating-point value down to the closest integer. This behavior differs from that of Math.round( ), which rounds up or down to the nearest integer. Also note that Math.floor( ) rounds negative numbers down (i.e., to be more negative), not up (i.e., closer to zero).

Example

a = Math.floor(1.99);    // Result is 1.0
b = Math.floor(1.01);    // Result is 1.0
c = Math.floor(1.0);     // Result is 1.0
d = Math.floor(-1.01);   // Result is -2.0

Name

Math.LN10: the mathematical constant loge2 — ECMAScript v1

Synopsis

Math.LN10

Description

Math.LN10 is log e 2, the natural logarithm of 10. This constant has a value of approximately 2.3025850929940459011.


Name

Math.LN2: the mathematical constant loge10 — ECMAScript v1

Synopsis

Math.LN2

Description

Math.LN2 is log e 10, the natural logarithm of 2. This constant has a value of approximately 0.69314718055994528623.


Name

Math.log( ): compute a natural logarithm — ECMAScript v1

Synopsis

Math.log(x)

Arguments

x

Any numeric value or expression greater than zero.

Returns

The natural logarithm of x.

Description

Math.log( ) computes log e x, the natural logarithm of its argument. The argument must be greater than zero.

You can compute the base-10 and base-2 logarithms of a number with these formulas:

log10x  = log10e · logex

log2x  = log2e · logex

These formulas translate into the following JavaScript functions:

function log10(x) { return Math.LOG10E * Math.log(x); }
function log2(x) { return  Math.LOG2E * Math.log(x); }

Name

Math.LOG10E: the mathematical constant log2 e — ECMAScript v1

Synopsis

Math.LOG10E

Description

Math.LOG10E is log2 e the base-10 logarithm of the constant e. It has a value of approximately 0.43429448190325181667.


Name

Math.LOG2E: the mathematical constant log10 e — ECMAScript v1

Synopsis

Math.LOG2E

Description

Math.LOG2E is log10 e the base-2 logarithm of the constant e. It has a value of approximately 1.442695040888963387.


Name

Math.max( ): return the largest argument — ECMAScript v1; enhanced in ECMAScript v3

Synopsis

Math.max(args...)

Arguments

args...

Zero or more values. Prior to ECMAScript v3, this method expects exactly two arguments.

Returns

The largest of the arguments. Returns -Infinity if there are no arguments. Returns NaN if any of the arguments is NaN or is a nonnumeric value that cannot be converted to a number.


Name

Math.min( ): return the smallest argument — ECMAScript v1; enhanced in ECMAScript v3

Synopsis

Math.min(args...)

Arguments

args...

Any number of arguments. Prior to ECMAScript v3, this function expects exactly two arguments.

Returns

The smallest of the specified arguments. Returns Infinity if there are no arguments. Returns NaN if any argument is NaN or is a nonnumeric value that cannot be converted to a number.


Name

Math.PI: the mathematical constant π — ECMAScript v1

Synopsis

Math.PI

Description

Math.PI is the constant π or pi, the ratio of the circumference of a circle to its diameter. It has a value of approximately 3.14159265358979.


Name

Math.pow( ): compute 'x'y — ECMAScript v1

Synopsis

Math.pow(x, y)

Arguments

x

The number to be raised to a power.

y

The power that x is to be raised to.

Returns

x to the power of y, x y

Description

Math.pow( ) computes x to the power of y. Any values of x and y may be passed to Math.pow( ). However, if the result is an imaginary or complex number, Math.pow( ) returns NaN. In practice, this means that if x is negative, y should be a positive or negative integer. Also, bear in mind that large exponents can easily cause floating-point overflow and return a value of Infinity.


Name

Math.random( ): return a pseudorandom number — ECMAScript v1

Synopsis

Math.random( )

Returns

A pseudorandom number greater than or equal to 0.0 and less than 1.0.


Name

Math.round( ): round to the nearest integer — ECMAScript v1

Synopsis

Math.round(x)

Arguments

x

Any number.

Returns

The integer closest to x.

Description

Math.round( ) rounds its argument up or down to the nearest integer. It rounds .5 up. For example, it rounds 2.5 to 3 and rounds −2.5 to −2.


Name

Math.sin( ): compute a sine — ECMAScript v1

Synopsis

Math.sin(x)

Arguments

x

An angle, in radians. To convert degrees to radians, multiply by 0.017453293 (2π/360).

Returns

The sine of x. This return value is between −1.0 and 1.0.


Name

Math.sqrt( ): compute a square root — ECMAScript v1

Synopsis

Math.sqrt(x)

Arguments

x

A numeric value greater than or equal to zero.

Returns

The square root of x. Returns NaN if x is less than zero.

Description

Math.sqrt( ) computes the square root of a number. Note, however, that you can compute arbitrary roots of a number with Math.pow( ). For example:

Math.cuberoot = function(x){ return Math.pow(x,1/3); }
Math.cuberoot(8);  // Returns 2

Name

Math.SQRT1_2: the mathematical constant 1/␁ — ECMAScript v1

Synopsis

Math.SQRT1_2

Description

Math.SQRT1_2 is 1/␁ the reciprocal of the square root of 2. This constant has a value of approximately 0.7071067811865476.


Name

Math.SQRT2: the mathematical constant ␁ — ECMAScript v1

Synopsis

Math.SQRT2

Description

Math.SQRT2 is the constant ␁, the square root of 2. This constant has a value of approximately 1.414213562373095.


Name

Math.tan( ): compute a tangent — ECMAScript v1

Synopsis

Math.tan(x)

Arguments

x

An angle, measured in radians. To convert degrees to radians, multiply the degree value by 0.017453293 (2π/360).

Returns

The tangent of the specified angle x.


Name

NaN: the not-a-number property — ECMAScript v1

Synopsis

NaN

Description

NaN is a global property that refers to the special numeric not-a-number value. The NaN property is not enumerated by for/in loops and cannot be deleted with the delete operator. Note that NaN is not a constant and can be set to any other value, something that you should take care not to do.

To determine if a value is not a number, use isNaN( ), because NaN always compares as nonequal to any other value, including itself!

See Also

Infinity, isNaN( ), Number.NaN


Name

Number: support for numbers — ECMAScript v1: Object → Number

Constructor

new Number(value)
Number(value)

Arguments

value

The numeric value of the Number object being created or a value to be converted to a number.

Returns

When Number( ) is used with the new operator as a constructor, it returns a newly constructed Number object. When Number( ) is invoked as a function without the new operator, it converts its argument to a primitive numeric value and returns that value (or NaN if the conversion failed).

Constants

Number.MAX_VALUE

The largest representable number.

Number.MIN_VALUE

The smallest representable number.

Number.NaN

Not-a-number value.

Number.NEGATIVE_INFINITY

Negative infinite value; returned on overflow.

Number.POSITIVE_INFINITY

Infinite value; returned on overflow.

Methods

toString( )

Converts a number to a string using a specified radix (base).

toLocaleString( )

Converts a number to a string using local number-formatting conventions.

toFixed( )

Converts a number to a string that contains a specified number of digits after the decimal place.

toExponential( )

Converts a number to a string using exponential notation with the specified number of digits after the decimal place.

toPrecision( )

Converts a number to a string using the specified number of significant digits. Uses exponential or fixed-point notation depending on the size of the number and the number of significant digits specified.

valueOf( )

Returns the primitive numeric value of a Number object.

Description

Numbers are a basic, primitive datatype in JavaScript. JavaScript also supports the Number object, which is a wrapper object around a primitive numeric value. JavaScript automatically converts between the primitive and object forms as necessary. You can explicitly create a Number object with the Number( ) constructor, although there is rarely any need to do so.

The Number( ) constructor can also be used without the new operator, as a conversion function. When invoked in this way, it attempts to convert its argument to a number and returns the primitive numeric value (or NaN) that results from the conversion.

The Number( ) constructor is also used as a placeholder for five useful numeric constants: the largest and smallest representable numbers, positive and negative infinity, and the special NaN value. Note that these values are properties of the Number( ) constructor function itself, not of individual number objects. For example, you can use the MAX_VALUE property as follows:

var biggest = Number.MAX_VALUE

but not like this:

var n = new Number(2);
var biggest = n.MAX_VALUE

By contrast, the toString( ) and other methods of the Number object are methods of each Number object, not of the Number( ) constructor function. As noted earlier, JavaScript automatically converts from primitive numeric values to Number objects whenever necessary. This means that you can use the Number methods with primitive numeric values as well as with Number objects.

var value = 1234;
var binary_value = n.toString(2);

See Also

Infinity, Math, NaN


Name

Number.MAX_VALUE: the maximum numeric value — ECMAScript v1

Synopsis

Number.MAX_VALUE

Description

Number.MAX_VALUE is the largest number representable in JavaScript. Its value is approximately 1.79E+308.


Name

Number.MIN_VALUE: the minimum numeric value — ECMAScript v1

Synopsis

Number.MIN_VALUE

Description

Number.MIN_VALUE is the smallest (closest to zero, not most negative) number representable in JavaScript. Its value is approximately 5E-324.


Name

Number.NaN: the special not-a-number value — ECMAScript v1

Synopsis

Number.NaN

Description

Number.NaN is a special value that indicates that the result of some mathematical operation (such as taking the square root of a negative number) is not a number. parseInt( ) and parseFloat( ) return this value when they cannot parse the specified string, and you might use Number.NaN in a similar way to indicate an error condition for some function that normally returns a valid number.

JavaScript prints the Number.NaN value as NaN. Note that the NaN value always compares as unequal to any other number, including NaN itself. Thus, you cannot check for the not-a-number value by comparing to Number.NaN; use the isNaN( ) function instead. In ECMAScript v1 and later, you can also use the predefined global property NaN instead of Number.NaN.

See Also

isNaN( ), NaN

Name

Number.NEGATIVE_INFINITY: negative infinity — ECMAScript v1

Synopsis

Number.NEGATIVE_INFINITY

Description

Number.NEGATIVE_INFINITY is a special numeric value that is returned when an arithmetic operation or mathematical function generates a negative value greater than the largest representable number in JavaScript (i.e., more negative than -Number.MAX_VALUE).

JavaScript displays the NEGATIVE_INFINITY value as -Infinity. This value behaves mathematically like infinity; for example, anything multiplied by infinity is infinity, and anything divided by infinity is zero. In ECMAScript v1 and later, you can also use -Infinity instead of Number.NEGATIVE_INFINITY.

See Also

Infinity, isFinite( )

Name

Number.POSITIVE_INFINITY: infinity — ECMAScript v1

Synopsis

Number.POSITIVE_INFINITY

Description

Number.POSITIVE_INFINITY is a special numeric value returned when an arithmetic operation or mathematical function overflows or generates a value greater than the largest representable number in JavaScript (i.e., greater than Number.MAX_VALUE). Note that when numbers "underflow," or become less than Number.MIN_VALUE, JavaScript converts them to zero.

JavaScript displays the POSITIVE_INFINITY value as Infinity. This value behaves mathematically like infinity; for example, anything multiplied by infinity is infinity, and anything divided by infinity is zero. In ECMAScript v1 and later, you can also use the predefined global property Infinity instead of Number.POSITIVE_INFINITY.

See Also

Infinity, isFinite( )

Name

Number.toExponential( ): format a number using exponential notation — ECMAScript v3

Synopsis

number.toExponential(digits)

Arguments

digits

The number of digits that appears after the decimal point. This may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, as many digits as necessary are used.

Returns

A string representation of number, in exponential notation, with one digit before the decimal place and digits digits after the decimal place. The fractional part of the number is rounded, or padded with zeros, as necessary, so that it has the specified length.

Throws

RangeError

If digits is too small or too large. Values between 0 and 20, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as well.

TypeError

If this method is invoked on an object that is not a Number.

Example

var n = 12345.6789;
n.toExponential(1);     // Returns 1.2e+4
n.toExponential(5);     // Returns 1.23457e+4
n.toExponential(10);    // Returns 1.2345678900e+4
n.toExponential( );         // Returns 1.23456789e+4

See Also

Number.toFixed( ), Number.toLocaleString( ), Number.toPrecision( ), Number.toString( )


Name

Number.toFixed( ): format a number using fixed-point notation — ECMAScript v3

Synopsis

number.toFixed(digits)

Arguments

digits

The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.

Returns

A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If number is greater than 1e+21, this method simply calls Number.toString( ) and returns a string in exponential notation.

Throws

RangeError

If digits is too small or too large. Values between 0 and 20, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as well.

TypeError

If this method is invoked on an object that is not a Number.

Example

var n = 12345.6789;
n.toFixed( );                 // Returns 12346: note rounding, no fractional part
n.toFixed(1);             // Returns 12345.7: note rounding
n.toFixed(6);             // Returns 12345.678900: note added zeros
(1.23e+20).toFixed(2);    // Returns 123000000000000000000.00
(1.23e-10).toFixed(2)     // Returns 0.00

See Also

Number.toExponential( ), Number.toLocaleString( ), Number.toPrecision( ), Number.toString( )


Name

Number.toLocaleString( ): convert a number to a locally formatted string — ECMAScript v3

Synopsis

number.toLocaleString( )

Returns

An implementation-dependent string representation of the number, formatted according to local conventions, which may affect such things as the punctuation characters used for the decimal point and the thousands separator.

Throws

TypeError

If this method is invoked on an object that is not a Number.

See Also

Number.toExponential( ), Number.toFixed( ), Number.toPrecision( ), Number.toString( )


Name

Number.toPrecision( ): format the significant digits of a number — ECMAScript v3

Synopsis

number.toPrecision(precision)

Arguments

precision

The number of significant digits to appear in the returned string. This may be a value between 1 and 21, inclusive. Implementations are allowed to optionally support larger and smaller values of precision. If this argument is omitted, the toString( ) method is used instead to convert the number to a base-10 value.

Returns

A string representation of number that contains precision significant digits. If precision is large enough to include all the digits of the integer part of number, the returned string uses fixed-point notation. Otherwise, exponential notation is used with one digit before the decimal place and precision−1 digits after the decimal place. The number is rounded or padded with zeros as necessary.

Throws

RangeError

If digits is too small or too large. Values between 1 and 21, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as well.

TypeError

If this method is invoked on an object that is not a Number.

Example

var n = 12345.6789;
n.toPrecision(1);   // Returns 1e+4
n.toPrecision(3);   // Returns 1.23e+4
n.toPrecision(5);   // Returns 12346: note rounding
n.toPrecision(10);  // Returns 12345.67890: note added zero

See Also

Number.toExponential( ), Number.toFixed( ), Number.toLocaleString( ), Number.toString( )


Name

Number.toString( ): convert a number to a string — ECMAScript v1: Overrides Object.toString( )

Synopsis

number.toString(radix)

Arguments

radix

An optional argument that specifies the radix, or base, between 2 and 36, in which the number should be represented. If omitted, base 10 is used. Note, however, that the ECMAScript specification allows an implementation to return any value if this argument is specified as any value other than 10.

Returns

A string representation of the number, in the specified base.

Throws

TypeError

If this method is invoked on an object that is not a Number.

Description

The toString( ) method of the Number object converts a number to a string. When the radix argument is omitted or is specified as 10, the number is converted to a base-10 string. Although the ECMAScript specification does not require implementations to honor any other values for radix, all implementations in common use accept values between 2 and 36.

See Also

Number.toExponential( ), Number.toFixed( ), Number.toLocaleString( ), Number.toPrecision( )


Name

Number.valueOf( ): return the primitive number value — ECMAScript v1: Overrides Object.valueOf( )

Synopsis

number.valueOf( )

Returns

The primitive number value of this Number object. It is rarely necessary to call this method explicitly.

Throws

TypeError

If this method is invoked on an object that is not a Number.

See Also

Object.valueOf( )

Name

Object: a superclass that contains features of all JavaScript objects — ECMAScript v1

Constructor

new Object( )
new Object(value)

Arguments

value

This optional argument specifies a primitive JavaScript value—a number, boolean, or string—that is to be converted to a Number, Boolean, or String object.

Returns

If no value argument is passed, this constructor returns a newly created Object instance. If a primitive value argument is specified, the constructor creates and returns a Number, Boolean, or String object wrapper for the primitive value. When the Object( ) constructor is called as a function, without the new operator, it behaves just as it does when used with the new operator.

Properties

constructor

A reference to the JavaScript function that was the constructor for the object.

Methods

hasOwnProperty( )

Checks whether an object has a locally defined (noninherited) property with a specified name.

isPrototypeOf( )

Checks whether this object is the prototype object of a specified object.

propertyIsEnumerable( )

Checks whether a named property exists and would be enumerated by a for/in loop.

toLocaleString( )

Returns a localized string representation of the object. The default implementation of this method simply calls toString( ), but subclasses may override it to provide localization.

toString( )

Returns a string representation of the object. The implementation of this method provided by the Object class is quite generic and does not provide much useful information. Subclasses of Object typically override this method by defining their own toString( ) method, which produces more useful output.

valueOf( )

Returns the primitive value of the object, if any. For objects of type Object, this method simply returns the object itself. Subclasses of Object, such as Number and Boolean, override this method to return the primitive value associated with the object.

Description

The Object class is a built-in datatype of the JavaScript language. It serves as the superclass for all other JavaScript objects; therefore, methods and behavior of the Object class are inherited by all other objects. The basic behavior of objects in JavaScript is explained in Chapter 7, Objects and Arrays.

In addition to the Object( ) constructor shown above, objects can also be created and initialized using the Object literal syntax described in Chapter 7, Objects and Arrays.

See Also

Array, Boolean, Function, Function.prototype, Number, String; Chapter 7, Objects and Arrays


Name

Object.constructor: an object's constructor function — ECMAScript v1

Synopsis

object.constructor

Description

The constructor property of any object is a reference to the function that was used as the constructor for that object. For example, if you create an array a with the Array( ) constructor, a.constructor is an Array:

a = new Array(1,2,3);   // Create an object
a.constructor == Array  // Evaluates to true

One common use of the constructor property is to determine the type of unknown objects. Given an unknown value, you can use the typeof operator to determine whether it is a primitive value or an object. If it is an object, you can use the constructor property to determine what type of object it is. For example, the following function determines whether a given value is an array:

function isArray(x) {
    return ((typeof x == "object") && (x.constructor == Array));
}

Note, however, that while this technique works for the objects built into core JavaScript, it is not guaranteed to work with host objects such as the Window object of client-side JavaScript. The default implementation of the Object.toString( ) method provides another way to determine the type of an unknown object.

See Also

Object.toString( )

Name

Object.hasOwnProperty( ): check whether a property is inherited — ECMAScript v3

Synopsis

object.hasOwnProperty(propname)

Arguments

propname

A string that contains the name of a property of object.

Returns

true if object has a noninherited property with the name specified by propname; false if object does not have a property with the specified name or if it inherits that property from its prototype object.

Description

As explained in Chapter 9, Classes, Constructors, and Prototypes, JavaScript objects may have properties of their own, and they may also inherit properties from their prototype object. The hasOwnProperty( ) method provides a way to distinguish between inherited properties and noninherited local properties.

Example

var o = new Object( );            // Create an object
o.x = 3.14;                      // Define a noninherited local property
o.hasOwnProperty("x");           // Returns true: x is a local property of o
o.hasOwnProperty("y");           // Returns false: o doesn't have a property y
o.hasOwnProperty("toString");    // Returns false: toString property is inherited

See Also

Function.prototype, Object.propertyIsEnumerable( ); Chapter 9, Classes, Constructors, and Prototypes


Name

Object.isPrototypeOf( ): is one object the prototype of another? — ECMAScript v3

Synopsis

object.isPrototypeOf(o)

Arguments

o

Any object.

Returns

true if object is the prototype of o; false if o is not an object or if object is not the prototype of o.

Description

As explained in Chapter 9, Classes, Constructors, and Prototypes, JavaScript objects inherit properties from their prototype object. The prototype of an object is referred to by the prototype property of the constructor function that creates and initializes the object. The isPrototypeOf( ) method provides a way to determine if one object is the prototype of another. This technique can be used to determine the class of an object.

Example

var o = new Object( );                               // Create an object
Object.prototype.isPrototypeOf(o)                // true: o is an object
Function.prototype.isPrototypeOf(o.toString);    // true: toString is a function
Array.prototype.isPrototypeOf([1,2,3]);          // true: [1,2,3] is an array
// Here is a way to perform a similar test
(o.constructor == Object);  // true: o was created with Object( ) constructor
(o.toString.constructor == Function);            // true: o.toString is a function
// Prototype objects themselves have prototypes. The following call
// returns true, showing that function objects inherit properties
// from Function.prototype and also from Object.prototype.
Object.prototype.isPrototypeOf(Function.prototype);

See Also

Function.prototype, Object.constructor; Chapter 9, Classes, Constructors, and Prototypes


Name

Object.propertyIsEnumerable( ): will property be seen by a for/in loop? — ECMAScript v3

Synopsis

object.propertyIsEnumerable(propname)

Arguments

propname

A string that contains the name of a property of object.

Returns

true if object has a noninherited property with the name specified by propname and if that property is enumerable, which means that it would be enumerated by a for/in loop on object.

Description

The for/in statement loops through the enumerable properties of an object. Not all properties of an object are enumerable, however: properties added to an object by JavaScript code are enumerable, but the predefined properties (such as methods) of built-in objects are not usually enumerable. The propertyIsEnumerable( ) method provides a way to distinguish between enumerable and nonenumerable properties. Note, however, that the ECMAScript specification states that propertyIsEnumerable( ) does not examine the prototype chain, which means it works only for local properties of an object and does not provide any way to test the enumerability of inherited properties.

Example

var o = new Object( );               // Create an object
o.x = 3.14;                         // Define a property
o.propertyIsEnumerable("x");        // true: property x is local and enumerable
o.propertyIsEnumerable("y");        // false: o doesn't have a property y
o.propertyIsEnumerable("toString"); // false: toString property is inherited
Object.prototype.propertyIsEnumerable("toString");  // false: nonenumerable

See Also

Function.prototype, Object.hasOwnProperty( ); Chapter 7, Objects and Arrays


Name

Object.toLocaleString( ): return an object's localized string representation — ECMAScript v3

Synopsis

object.toString( )

Returns

A string representing the object.

Description

This method is intended to return a string representation of the object, localized as appropriate for the current locale. The default toLocaleString( ) method provided by the Object class simply calls the toString( ) method and returns the nonlocalized string that it returns. Note, however, that other classes, including Array, Date, and Number, define their own versions of this method to perform localized string conversions. When defining your own classes, you may want to override this method as well.

See Also

Array.toLocaleString( ), Date.toLocaleString( ), Number.toLocaleString( ), Object.toString( )


Name

Object.toString( ): define an object's string representation — ECMAScript v1

Synopsis

object.toString( )

Returns

A string representing the object.

Description

The toString( ) method is not one you often call explicitly in your JavaScript programs. Instead, you define this method in your objects, and the system calls it whenever it needs to convert your object to a string.

The JavaScript system invokes the toString( ) method to convert an object to a string whenever the object is used in a string context. For example, an object is converted to a string when it is passed to a function that expects a string argument:

alert(my_object);

Similarly, objects are converted to strings when they are concatenated to strings with the + operator:

var msg = 'My object is: ' + my_object;

The toString( ) method is invoked without arguments and should return a string. To be useful, the string you return should be based, in some way, on the value of the object for which the method was invoked.

When you define a custom class in JavaScript, it is good practice to define a toString( ) method for the class. If you do not, the object inherits the default toString( ) method from the Object class. This default method returns a string of the form:

[objectclass]

where class is the class of the object: a value such as "Object", "String", "Number", "Function", "Window", "Document", and so on. This behavior of the default toString( ) method is occasionally useful to determine the type or class of an unknown object. Because most objects have a custom version of toString( ), however, you must explicitly invoke the Object.toString( ) method on an object o with code like this:

Object.prototype.toString.apply(o);

Note that this technique for identifying unknown objects works only for built-in objects. If you define your own object class, it will have a class of "Object". In this case, you can use the Object.constructor property to obtain more information about the object.

The toString( ) method can be quite useful when you are debugging JavaScript programs; it allows you to print objects and see their value. For this reason alone, it is a good idea to define a toString( ) method for every object class you create.

Although the toString( ) method is usually invoked automatically by the system, there are times when you may invoke it yourself. For example, you might want to do an explicit conversion of an object to a string in a situation where JavaScript does not do it automatically for you:

y = Math.sqrt(x);       // Compute a number
ystr = y.toString( );       // Convert it to a string

Note in this example that numbers have a built-in toString( ) method you can use to force a conversion.

In other circumstances, you can choose to use a toString( ) call even in a context where JavaScript does the conversion automatically. Using toString( ) explicitly can help to make your code clearer:

alert(my_obj.toString( ));

See Also

Object.constructor, Object.toLocaleString( ), Object.valueOf( )


Name

Object.valueOf( ): the primitive value of the specified object — ECMAScript v1

Synopsis

object.valueOf( )

Returns

The primitive value associated with the object, if any. If there is no value associated with object, returns the object itself.

Description

The valueOf( ) method of an object returns the primitive value associated with that object, if there is one. For objects of type Object, there is no primitive value, and this method simply returns the object itself.

For objects of type Number, however, valueOf( ) returns the primitive numeric value represented by the object. Similarly, it returns the primitive boolean value associated with a Boolean object and the string associated with a String object.

It is rarely necessary to invoke the valueOf( ) method yourself. JavaScript does this automatically whenever an object is used where a primitive value is expected. In fact, because of this automatic invocation of the valueOf( ) method, it is difficult to even distinguish between primitive values and their corresponding objects. The typeof operator shows you the difference between strings and String objects for example, but in practical terms, you can use them equivalently in your JavaScript code.

The valueOf( ) methods of the Number, Boolean, and String objects convert these wrapper objects to the primitive values they represent. The Object( ) constructor performs the opposite operation when invoked with a number, boolean, or string argument: it wraps the primitive value in an appropriate object wrapper. JavaScript performs this primitive-to-object conversion for you in almost all circumstances, so it is rarely necessary to invoke the Object( ) constructor in this way.

In some circumstances, you may want to define a custom valueOf( ) method for your own objects. For example, you might define a JavaScript object type to represent complex numbers (a real number plus an imaginary number). As part of this object type, you would probably define methods for performing complex addition, multiplication, and so on (see Example 9-2, “A complex number class”). But you might also want to treat your complex numbers like ordinary real numbers by discarding the imaginary part. To achieve this, you might do something like the following:

Complex.prototype.valueOf = new Function("return this.real");

With this valueOf( ) method defined for your Complex object type, you can, for example, pass one of your complex number objects to Math.sqrt( ), which computes the square root of the real portion of the complex number.

See Also

Object.toString( )

Name

Packages: the root JavaPackage — LiveConnect

Synopsis

Packages

Description

In JavaScript implementations that include LiveConnect or other technology for scripting Java, the global Packages property is a JavaPackage object whose properties are all the package roots known to the Java interpreter. For example, Packages.javax.swing refers to the Java package javax.swing. The global property java is a shortcut for Packages.java.

See Also

java, JavaPackage; Chapter 12, Scripting Java


Name

parseFloat( ): convert a string to a number — ECMAScript v1

Synopsis

parseFloat(s)

Arguments

s

The string to be parsed and converted to a number.

Returns

The parsed number, or NaN if s does not begin with a valid number. In JavaScript 1.0, parseFloat( ) returns 0 instead of NaN when s cannot be parsed as a number.

Description

parseFloat( ) parses and returns the first number that occurs in s. Parsing stops, and the value is returned, when parseFloat( ) encounters a character in s that is not a valid part of the number. If s does not begin with a number that parseFloat( ) can parse, the function returns the not-a-number value NaN. Test for this return value with the isNaN( ) function. If you want to parse only the integer portion of a number, use parseInt( ) instead of parseFloat( ).

See Also

isNaN( ), parseInt( )

Name

parseInt( ): convert a string to an integer — ECMAScript v1

Synopsis

parseInt(s)

parseInt(s, radix)

Arguments

s

The string to be parsed.

radix

An optional integer argument that represents the radix (i.e., base) of the number to be parsed. If this argument is omitted or is 0, the number is parsed in base 10—or in base 16 if it begins with 0x or 0X. If this argument is less than 2 or greater than 36, parseInt( ) returns NaN.

Returns

The parsed number, or NaN if s does not begin with a valid integer. In JavaScript 1.0, parseInt( ) returns 0 instead of NaN when it cannot parse s.

Description

parseInt( ) parses and returns the first number (with an optional leading minus sign) that occurs in s. Parsing stops, and the value is returned, when parseInt( ) encounters a character in s that is not a valid digit for the specified radix. If s does not begin with a number that parseInt( ) can parse, the function returns the not-a-number value NaN. Use the isNaN( ) function to test for this return value.

The radix argument specifies the base of the number to be parsed. Specifying 10 makes parseInt( ) parse a decimal number. The value 8 specifies that an octal number (using digits 0 through 7) is to be parsed. The value 16 specifies a hexadecimal value, using digits 0 through 9 and letters A through F. radix can be any value between 2 and 36.

If radix is 0 or is not specified, parseInt( ) tries to determine the radix of the number from s. If s begins (after an optional minus sign) with 0x, parseInt( ) parses the remainder of s as a hexadecimal number. If s begins with a 0, the ECMAScript v3 standard allows an implementation of parseInt( ) to interpret the following characters as an octal number or as a decimal number. Otherwise, if s begins with a digit from 1 through 9, parseInt( ) parses it as a decimal number.

Example

parseInt("19", 10);  // Returns 19  (10 + 9)
parseInt("11", 2);   // Returns 3   (2 + 1)
parseInt("17", 8);   // Returns 15  (8 + 7)
parseInt("1f", 16);  // Returns 31  (16 + 15)
parseInt("10");      // Returns 10
parseInt("0x10");    // Returns 16
parseInt("010");     // Ambiguous: returns 10 or 8

Bugs

When no radix is specified, ECMAScript v3 allows an implementation to parse a string that begins with 0 (but not 0x or 0X) as an octal or as a decimal number. To avoid this ambiguity, you should explicitly specify a radix or leave the radix unspecified only when you are sure that all numbers to be parsed will be decimal numbers, or hexadecimal numbers with the 0x or 0X prefix.

See Also

isNaN( ), parseFloat( )

Name

RangeError: thrown when a number is out of its legal range — ECMAScript v3: Object → Error → RangeError

Constructor

new RangeError( )
new RangeError(message)

Arguments

message

An optional error message that provides details about the exception. If specified, this argument is used as the value for the message property of the RangeError object.

Returns

A newly constructed RangeError object. If the message argument is specified, the Error object uses it as the value of its message property; otherwise, it uses an implementation-defined default string as the value of that property. When the RangeError( ) constructor is called as a function, without the new operator, it behaves just as it would when called with the new operator.

Properties

message

An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string. See Error.message for details.

name

A string that specifies the type of the exception. All RangeError objects inherit the value "RangeError" for this property.

Description

An instance of the RangeError class is thrown when a numeric value is not in its legal range. For example, setting the length of an array to a negative number causes a RangeError to be thrown. See Error for details about throwing and catching exceptions.

See Also

Error, Error.message, Error.name


Name

ReferenceError: thrown when reading a variable that does not exist — ECMAScript v3: Object → Error → ReferenceError

Constructor

new ReferenceError( )
new ReferenceError(message)

Arguments

message

An optional error message that provides details about the exception. If specified, this argument is used as the value for the message property of the ReferenceError object.

Returns

A newly constructed ReferenceError object. If the message argument is specified, the Error object uses it as the value of its message property; otherwise, it uses an implementation-defined default string as the value of that property. When the ReferenceError( ) constructor is called as a function, without the new operator, it behaves just as it would with the new operator.

Properties

message

An error message that provides details about the exception. This property holds the string passed to the constructor or an implementation-defined default string. See Error.message for details.

name

A string that specifies the type of the exception. All ReferenceError objects inherit the value "ReferenceError" for this property.

Description

An instance of the ReferenceError class is thrown when you attempt to read the value of a variable that does not exist. See Error for details about throwing and catching exceptions.

See Also

Error, Error.message, Error.name

Name

RegExp: regular expressions for pattern matching — ECMAScript v3: Object → RegExp

Literal Syntax

/pattern/attributes

Constructor

new RegExp(pattern, attributes)

Arguments

pattern

A string that specifies the pattern of the regular expression or another regular expression.

attributes

An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively. The "m" attribute is not available prior to ECMAScript standardization. If the pattern argument is a regular expression instead of a string, this argument must be omitted.

Returns

A new RegExp object, with the specified pattern and flags. If the pattern argument is a regular expression rather than a string, the RegExp( ) constructor creates a new RegExp object using the same pattern and flags as the specified RegExp. If RegExp( ) is called as a function without the new operator, it behaves just as it would with the new operator, except when pattern is a regular expression; in that case, it simply returns pattern instead of creating a new RegExp object.

Throws

SyntaxError

If pattern is not a legal regular expression, or if attributes contains characters other than "g", "i", and "m".

TypeError

If pattern is a RegExp object, and the attributes argument is not omitted.

Instance Properties

global

Whether the RegExp has the "g" attribute.

ignoreCase

Whether the RegExp has the "i" attribute.

lastIndex

The character position of the last match; used for finding multiple matches in a string.

multiline

Whether the RegExp has the "m" attribute.

source

The source text of the regular expression.

Methods

exec( )

Performs powerful, general-purpose pattern matching.

test( )

Tests whether a string contains a pattern.

Description

The RegExp object represents a regular expression, a powerful tool for performing pattern matching on strings. See Chapter 11, Pattern Matching with Regular Expressions for complete details on regular-expression syntax and use.


Name

RegExp.exec( ): general-purpose pattern matching — ECMAScript v3

Synopsis

regexp.exec(string)

Arguments

string

The string to be searched.

Returns

An array containing the results of the match or null if no match was found. The format of the returned array is described below.

Throws

TypeError

If this method is invoked on an object that is not a RegExp.

Description

exec( ) is the most powerful of all the RegExp and String pattern-matching methods. It is a general-purpose method that is somewhat more complex to use than RegExp.test( ), String.search( ), String.replace( ), and String.match( ).

exec( ) searches string for text that matches regexp. If it finds a match, it returns an array of results; otherwise, it returns null. Element 0 of the returned array is the matched text. Element 1 is the text that matched the first parenthesized subexpression, if any, within regexp. Element 2 contains the text that matched the second subexpression, and so on. The array length property specifies the number of elements in the array, as usual. In addition to the array elements and the length property, the value returned by exec( ) also has two other properties. The index property specifies the character position of the first character of the matched text. The input property refers to string. This returned array is the same as the array that is returned by the String.match( ) method, when invoked on a nonglobal RegExp object.

When exec( ) is invoked on a nonglobal pattern, it performs the search and returns the result described earlier. When regexp is a global regular expression, however, exec( ) behaves in a slightly more complex way. It begins searching string at the character position specified by the lastIndex property of regexp. When it finds a match, it sets lastIndex to the position of the first character after the match. This means that you can invoke exec( ) repeatedly in order to loop through all matches in a string. When exec( ) cannot find any more matches, it returns null and resets lastIndex to zero. If you begin searching a new string immediately after successfully finding a match in another string, you must be careful to manually reset lastIndex to zero.

Note that exec( ) always includes full details of every match in the array it returns, whether or not regexp is a global pattern. This is where exec( ) differs from String.match( ), which returns much less information when used with global patterns. Calling the exec( ) method repeatedly in a loop is the only way to obtain complete pattern-matching information for a global pattern.

Example

You can use exec( ) in a loop to find all matches within a string. For example:

var pattern = /\bJava\w*\b/g;
var text = "JavaScript is more fun than Java or JavaBeans!";
var result;
while((result = pattern.exec(text)) != null) {
    alert("Matched '" + result[0] +
          "' at position " + result.index +
          " next search begins at position " + pattern.lastIndex);
}

See Also

RegExp.lastIndex, RegExp.test( ), String.match( ), String.replace( ), String.search( ); Chapter 11, Pattern Matching with Regular Expressions


Name

RegExp.global: whether a regular expression matches globally — ECMAScript v3

Synopsis

regexp.global

Description

global is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs global matching—i.e., whether it was created with the "g" attribute.


Name

RegExp.ignoreCase: whether a regular expression is case-insensitive — ECMAScript v3

Synopsis

regexp.ignoreCase

Description

ignoreCase is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs case-insensitive matching—i.e., whether it was created with the "i" attribute.


Name

RegExp.lastIndex: the starting position of the next match — ECMAScript v3

Synopsis

regexp.lastIndex

Description

lastIndex is a read/write property of RegExp objects. For regular expressions with the "g" attribute set, it contains an integer that specifies the character position immediately following the last match found by the RegExp.exec( ) and RegExp.test( ) methods. These methods use this property as the starting point for the next search they conduct. This allows you to call those methods repeatedly, to loop through all matches in a string. Note that lastIndex is not used by RegExp objects that do not have the "g" attribute set and do not represent global patterns.

This property is read/write, so you can set it at any time to specify where in the target string the next search should begin. exec( ) and test( ) automatically reset lastIndex to 0 when they fail to find a match (or another match). If you begin to search a new string after a successful match of some other string, you have to explicitly set this property to 0.

See Also

RegExp.exec( ), RegExp.test( )


Name

RegExp.source: the text of the regular expression — ECMAScript v3

Synopsis

regexp.source

Description

source is a read-only string property of RegExp objects. It contains the text of the RegExp pattern. This text does not include the delimiting slashes used in regular-expression literals, and it does not include the "g", "i", and "m" attributes.


Name

RegExp.test( ): test whether a string matches a pattern — ECMAScript v3

Synopsis

regexp.test(string)

Arguments

string

The string to be tested.

Returns

true if string contains text that matches regexp; false otherwise.

Throws

TypeError

If this method is invoked on an object that is not a RegExp.

Description

test( ) tests string to see if it contains text that matches regexp. If so, it returns true; otherwise, it returns false. Calling the test( ) method of a RegExp r and passing it the string s is equivalent to the following expression:

(r.exec(s) != null)

Example

var pattern = /java/i;
pattern.test("JavaScript");   // Returns true
pattern.test("ECMAScript");   // Returns false

See Also

RegExp.exec( ), RegExp.lastIndex, String.match( ), String.replace( ), String.substring( ); Chapter 11, Pattern Matching with Regular Expressions


Name

RegExp.toString( ): convert a regular expression to a string — ECMAScript v3: Overrides Object.toString( )

Synopsis

regexp.toString( )

Returns

A string representation of regexp.

Throws

TypeError

If this method is invoked on an object that is not a RegExp.

Description

The RegExp.toString( ) method returns a string representation of a regular expression in the form of a regular-expression literal.

Note that implementations are not required to add escape sequences to ensure that the returned string is a legal regular-expression literal. Consider the regular expression created by the expression new RegExp("/","g"). An implementation of RegExp.toString( ) could return ///g for this regular expression; it could also add an escape sequence and return /\//g.


Name

String: support for strings — ECMAScript v1: Object → String

Constructor

new String(s) // Constructor function
String(s)     // Conversion function

Arguments

s

The value to be stored in a String object or converted to a primitive string.

Returns

When String( ) is used as a constructor with the new operator, it returns a String object, which holds the string s or the string representation of s. When the String( ) constructor is used without the new operator, it simply converts s to a primitive string and returns the converted value.

Properties

length

The number of characters in the string.

Methods

charAt( )

Extracts the character at a given position from a string.

charCodeAt( )

Returns the encoding of the character at a given position in a string.

concat( )

Concatenates one or more values to a string.

indexOf( )

Searches the string for a character or substring.

lastIndexOf( )

Searches the string backward for a character or substring.

localeCompare( )

Compares strings using locale-specific ordering.

match( )

Performs pattern matching with a regular expression.

replace( )

Performs a search-and-replace operation with a regular expression.

search( )

Searches a string for a substring that matches a regular expression.

slice( )

Returns a slice or substring of a string.

split( )

Splits a string into an array of strings, breaking at a specified delimiter string or regular expression.

substr( )

Extracts a substring of a string; a variant of substring( ).

substring( )

Extracts a substring of a string.

toLowerCase( )

Returns a copy of the string, with all characters converted to lowercase.

toString( )

Returns the primitive string value.

toUpperCase( )

Returns a copy of the string, with all characters converted to uppercase.

valueOf( )

Returns the primitive string value.

Static Methods

String.fromCharCode( )

Creates a new string using the character codes passed as arguments.

HTML Methods

Since the earliest days of JavaScript, the String class has defined a number of methods that return a string modified by placing it within HTML tags. These methods have never been standardized by ECMAScript but can be useful in both client- and server-side JavaScript code that dynamically generates HTML. If you are willing to use nonstandard methods, you might create the HTML source for a bold, red hyperlink with code like this:

var s = "click here!";
var html = s.bold( ).link("javascript:alert('hello')").fontcolor("red");

Because these methods are not standardized, they do not have individual reference entries in the pages that follow:

anchor( name )

Returns a copy of the string, in an <a name=> environment.

big( )

Returns a copy of the string, in a <big> environment.

blink( )

Returns a copy of the string, in a <blink> environment.

bold( )

Returns a copy of the string, in a <b> environment.

fixed( )

Returns a copy of the string, in a <tt> environment.

fontcolor( color )

Returns a copy of the string, in a <font color=> environment.

fontsize( size )

Returns a copy of the string, in a <font size=> environment.

italics( )

Returns a copy of the string, in an <i> environment.

link( url )

Returns a copy of the string, in an <a href=> environment.

small( )

Returns a copy of the string, in a <small> environment.

strike( )

Returns a copy of the string, in a <strike> environment.

sub( )

Returns a copy of the string, in a <sub>

sup( )

Returns a copy of the string, in a <sup> environment.

Description

Strings are a primitive datatype in JavaScript. The String class type exists to provide methods for operating on primitive string values. The length property of a String object specifies the number of characters in the string. The String class defines a number of methods for operating on strings; for example, there are methods for extracting a character or a substring from the string or searching for a character or a substring. Note that JavaScript strings are immutable: none of the methods defined by the String class allows you to change the contents of a string. Instead, methods such as String.toUpperCase( ) return an entirely new string, without modifying the original.

In implementations of JavaScript derived from the original Netscape code base (such as the implementation in Firefox), strings behave like read-only arrays of characters. For example, to extract the third character from a string s, you can write s[2] instead of the more standard s.charAt(2). In addition, when the for/in statement is applied to a string, it enumerates these array indexes for each character in the string. (Note, however, that the length property is not enumerated, as per the ECMAScript specification.) Because this string-as-array behavior is not standard, you should avoid using it.


Name

String.charAt( ): get the 'n'th character from a string — ECMAScript v1

Synopsis

string.charAt(n)

Arguments

n

The index of the character that should be returned from string.

Returns

The nth character of string.

Description

String.charAt( ) returns the nth character of the string string. The first character of the string is numbered 0. If n is not between 0 and string.length−1, this method returns an empty string. Note that JavaScript does not have a character data type that is distinct from the string type, so the returned character is a string of length 1.

See Also

String.charCodeAt( ), String.indexOf( ), String.lastIndexOf( )


Name

String.charCodeAt( ): get the 'n'th character code from a string — ECMAScript v1

Synopsis

string.charCodeAt(n)

Arguments

n

The index of the character whose encoding is to be returned.

Returns

The Unicode encoding of the nth character within string. This return value is a 16-bit integer between 0 and 65535.

Description

charCodeAt( ) is like charAt( ), except that it returns the character encoding at a specific location, rather than returning a substring that contains the character itself. If n is negative or greater than or equal to the string length, charCodeAt( ) returns NaN.

See String.fromCharCode( ) for a way to create a string from Unicode encodings.

See Also

String.charAt( ), String.fromCharCode( )


Name

String.concat( ): concatenate strings — ECMAScript v3

Synopsis

string.concat(value, ...)

Arguments

value, ...

One or more values to be concatenated to string.

Returns

A new string that results from concatenating each of the arguments to string.

Description

concat( ) converts each of its arguments to a string (if necessary) and appends them, in order, to the end of string. It returns the resulting concatenation. Note that string itself is not modified.

String.concat( ) is an analog to Array.concat( ). Note that it is often easier to use the + operator to perform string concatenation.

See Also

Array.concat( )

Name

String.fromCharCode( ): create a string from character encodings — ECMAScript v1

Synopsis

String.fromCharCode(c1, c2, ...)

Arguments

c1, c2, ...

Zero or more integers that specify the Unicode encodings of the characters in the string to be created.

Returns

A new string containing characters with the specified encodings.

Description

This static method provides a way to create a string by specifying the individual numeric Unicode encodings of its characters. Note that as a static method, fromCharCode( ) is a property of the String( ) constructor and is not actually a method of strings or String objects.

String.charCodeAt( ) is a companion instance method that provides a way to obtain the encodings of the individual characters of a string.

Example

// Create the string "hello"
var s = String.fromCharCode(104, 101, 108, 108, 111);

See Also

String.charCodeAt( )

Name

String.indexOf( ): search a string — ECMAScript v1

Synopsis

string.indexOf(substring)

string.indexOf(substring, start)

Arguments

substring

The substring that is to be searched for within string.

start

An optional integer argument that specifies the position within string at which the search is to start. Legal values are 0 (the position of the first character in the string) to string .length−1 (the position of the last character in the string). If this argument is omitted, the search begins at the first character of the string.

Returns

The position of the first occurrence of substring within string that appears after the start position, if any, or −1 if no such occurrence is found.

Description

String.indexOf( ) searches the string string from beginning to end to see if it contains an occurrence of substring. The search begins at position start within string, or at the beginning of string if start is not specified. If an occurrence of substring is found, String.indexOf( ) returns the position of the first character of the first occurrence of substring within string. Character positions within string are numbered starting with zero.

If no occurrence of substring is found within string, String.indexOf( ) returns −1.

See Also

String.charAt( ), String.lastIndexOf( ), String.substring( )


Name

String.lastIndexOf( ): search a string backward — ECMAScript v1

Synopsis

string.lastIndexOf(substring)

string.lastIndexOf(substring, start)

Arguments

substring

The substring to be searched for within string.

start

An optional integer argument that specifies the position within string where the search is to start. Legal values are from 0 (the position of the first character in the string) to string .length−1 (the position of the last character in the string). If this argument is omitted, the search begins with the last character of the string.

Returns

The position of the last occurrence of substring within string that appears before the start position, if any, or −1 if no such occurrence is found within string.

Description

String.lastIndexOf( ) searches the string from end to beginning to see if it contains an occurrence of substring. The search begins at position start within string, or at the end of string if start is not specified. If an occurrence of substring is found, String.lastIndexOf( ) returns the position of the first character of that occurrence. Since this method searches from end to beginning of the string, the first occurrence found is the last one in the string that occurs before the start position.

If no occurrence of substring is found, String.lastIndexOf( ) returns −1.

Note that although String.lastIndexOf( ) searches string from end to beginning, it still numbers character positions within string from the beginning. The first character of the string has position 0, and the last has position string .length−1.

See Also

String.charAt( ), String.indexOf( ), String.substring( )


Name

String.length: the length of a string — ECMAScript v1

Synopsis

string.length

Description

The String.length property is a read-only integer that indicates the number of characters in the specified string. For any string s, the index of the last character is s .length−1. The length property of a string is not enumerated by a for/in loop and may not be deleted with the delete operator.


Name

String.localeCompare( ): compare one string to another, using locale-specific ordering — ECMAScript v3

Synopsis

string.localeCompare(target)

Arguments

target

A string to be compared, in a locale-sensitive fashion, with string.

Returns

A number that indicates the result of the comparison. If string is "less than" target, localeCompare( ) returns a number less than zero. If string is "greater than" target, the method returns a number greater than zero. And if the strings are identical or indistinguishable according to the locale ordering conventions, the method returns 0.

Description

When the < and > operators are applied to strings, they compare those strings using only the Unicode encodings of those characters and do not consider the collation order of the current locale. The ordering produced in this way is not always correct. Consider Spanish, for example, in which the letters "ch" are traditionally sorted as if they were a single letter that appeared between the letters "c" and "d".

localeCompare( ) provides a way to compare strings that does take the collation order of the default locale into account. The ECMAScript standard does not specify how the locale-specific comparison is done; it merely specifies that this function utilize the collation order provided by the underlying operating system.

Example

You can use code like the following to sort an array of strings into a locale-specific ordering:

var strings;  // The array of strings to sort; initialized elsewhere
strings.sort(function(a,b) { return a.localeCompare(b) });

Name

String.match( ): find one or more regular-expression matches — ECMAScript v3

Synopsis

string.match(regexp)

Arguments

regexp

A RegExp object that specifies the pattern to be matched. If this argument is not a RegExp, it is first converted to one by passing it to the RegExp( ) constructor.

Returns

An array containing the results of the match. The contents of the array depend on whether regexp has the global "g" attribute set. Details on this return value are given in the Description.

Description

match( ) searches string for one or more matches of regexp. The behavior of this method depends significantly on whether regexp has the "g" attribute or not (see Chapter 11, Pattern Matching with Regular Expressions for full details on regular expressions).

If regexp does not have the "g" attribute, match( ) searches string for a single match. If no match is found, match( ) returns null. Otherwise, it returns an array containing information about the match that it found. Element 0 of the array contains the matched text. The remaining elements contain the text that matches any parenthesized subexpressions within the regular expression. In addition to these normal array elements, the returned array also has two object properties. The index property of the array specifies the character position within string of the start of the matched text. Also, the input property of the returned array is a reference to string itself.

If regexp has the "g" flag, match( ) does a global search, searching string for all matching substrings. It returns null if no match is found, and it returns an array if one or more matches are found. The contents of this returned array are quite different for global matches, however. In this case, the array elements contain each of the matched substrings within string. The returned array does not have index or input properties in this case. Note that for global matches, match( ) does not provide information about parenthesized subexpressions, nor does it specify where within string each match occurred. If you need to obtain this information for a global search, you can use RegExp.exec( ).

Example

The following global match finds all numbers within a string:

"1 plus 2 equals 3".match(/\d+/g)  // Returns ["1", "2", "3"]

The following nonglobal match uses a more complex regular expression with several parenthesized subexpressions. It matches a URL, and its subexpressions match the protocol, host, and path portions of the URL:

var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = "Visit my home page at http://www.isp.com/~david";
var result = text.match(url);
if (result != null) {
    var fullurl = result[0];   // Contains "http://www.isp.com/~david"
    var protocol = result[1];  // Contains "http"
    var host = result[2];      // Contains "www.isp.com"
    var path = result[3];      // Contains "~david"
}

See Also

RegExp, RegExp.exec( ), RegExp.test( ), String.replace( ), String.search( ); Chapter 11, Pattern Matching with Regular Expressions


Name

String.replace( ): replace substring(s) matching a regular expression — ECMAScript v3

Synopsis

string.replace(regexp, replacement)

Arguments

regexp

The RegExp object that specifies the pattern to be replaced. If this argument is a string, it is used as a literal text pattern to be searched for; it is not first converted to a RegExp object.

replacement

A string that specifies the replacement text, or a function that is invoked to generate the replacement text. See the Description section for details.

Returns

A new string, with the first match, or all matches, of regexp replaced with replacement.

Description

replace( ) performs a search-and-replace operation on string. It searches string for one or more substrings that match regexp and replaces them with replacement. If regexp has the global "g" attribute specified, replace( ) replaces all matching substrings. Otherwise, it replaces only the first matching substring.

replacement may be a string or a function. If it is a string, each match is replaced by the string. Note that the $ character has special meaning within the replacement string. As shown in the following table, it indicates that a string derived from the pattern match is used in the replacement.

Characters

Replacement

$1, $2, ..., $99

The text that matched the 1st through 99th parenthesized subexpression within regexp

$&

The substring that matched regexp

$'

The text to the left of the matched substring

$'

The text to the right of the matched substring

$$

A literal dollar sign

ECMAScript v3 specifies that the replacement argument to replace( ) may be a function instead of a string. In this case, the function is invoked for each match, and the string it returns is used as the replacement text. The first argument to the function is the string that matches the pattern. The next arguments are the strings that match any parenthesized subexpressions within the pattern; there may be zero or more of these arguments. The next argument is an integer that specifies the position within string at which the match occurred, and the final argument to the replacement function is string itself.

Example

To ensure that the capitalization of the word "JavaScript" is correct:

text.replace(/javascript/i, "JavaScript");

To convert a single name from "Doe, John" format to "John Doe" format:

name.replace(/(\w+)\s*,\s*(\w+)/, "$2 $1");

To replace all double quotes with double back and forward single quotes:

text.replace(/"([^"]*)"/g, "''$1''");

To capitalize the first letter of all words in a string:

text.replace(/\b\w+\b/g, function(word) {
                           return word.substring(0,1).toUpperCase( ) +
                                  word.substring(1);
                         });

See Also

RegExp, RegExp.exec( ), RegExp.test( ), String.match( ), String.search( ); Chapter 11, Pattern Matching with Regular Expressions


Name

String.search( ): search for a regular expression — ECMAScript v3

Synopsis

string.search(regexp)

Arguments

regexp

A RegExp object that specifies the pattern to be searched for in string. If this argument is not a RegExp, it is first converted to one by passing it to the RegExp( ) constructor.

Returns

The position of the start of the first substring of string that matches regexp, or −1 if no match is found.

Description

search( ) looks for a substring matching regexp within string and returns the position of the first character of the matching substring, or −1 if no match was found.

search( ) does not do global matches; it ignores the g flag. It also ignores the lastIndex property of regexp and always searches from the beginning of the string, which means that it always returns the position of the first match in string.

Example

var s = "JavaScript is fun";
s.search(/script/i)  // Returns 4
s.search(/a(.)a/)    // Returns 1

See Also

RegExp, RegExp.exec( ), RegExp.test( ), String.match( ), String.replace( ); Chapter 11, Pattern Matching with Regular Expressions


Name

String.slice( ): extract a substring — ECMAScript v3

Synopsis

string.slice(start, end)

Arguments

start

The string index where the slice is to begin. If negative, this argument specifies a position measured from the end of the string. That is, −1 indicates the last character, −2 indicates the second from last character, and so on.

end

The string index immediately after the end of the slice. If not specified, the slice includes all characters from start to the end of the string. If this argument is negative, it specifies a position measured from the end of the string.

Returns

A new string that contains all the characters of string from and including start, and up to but not including end.

Description

slice( ) returns a string containing a slice, or substring, of string. It does not modify string.

The String methods slice( ), substring( ), and the deprecated substr( ) all return specified portions of a string. slice( ) is more flexible than substring( ) because it allows negative argument values. slice( ) differs from substr( ) in that it specifies a substring with two character positions, while substr( ) uses one position and a length. Note also that String.slice( ) is an analog of Array.slice( ).

Example

var s = "abcdefg";
s.slice(0,4)    // Returns "abcd"
s.slice(2,4)    // Returns "cd"
s.slice(4)      // Returns "efg"
s.slice(3,-1)   // Returns "def"
s.slice(3,-2)   // Returns "de"
s.slice(-3,-1)  // Should return "ef"; returns "abcdef" in IE 4

Bugs

Negative values for start do not work in Internet Explorer 4 (but they do in later versions of IE). Instead of specifying a character position measured from the end of the string, they specify character position 0.

See Also

Array.slice( ), String.substring( )

Name

String.split( ): break a string into an array of strings — ECMAScript v3

Synopsis

string.split(delimiter, limit)

Arguments

delimiter

The string or regular expression at which the string splits.

limit

This optional integer specifies the maximum length of the returned array. If specified, no more than this number of substrings will be returned. If not specified, the entire string will be split, regardless of its length.

Returns

An array of strings, created by splitting string into substrings at the boundaries specified by delimiter. The substrings in the returned array do not include delimiter itself, except in the case noted in the Description.

Description

The split( ) method creates and returns an array of as many as limit substrings of the specified string. These substrings are created by searching the string from start to end for text that matches delimiter and breaking the string before and after that matching text. The delimiting text is not included in any of the returned substrings, except as noted at the end of this section. Note that if the delimiter matches the beginning of the string, the first element of the returned array will be an empty string—the text that appears before the delimiter. Similarly, if the delimiter matches the end of the string, the last element of the array (assuming no conflicting limit) will be the empty string.

If no delimiter is specified, the string is not split at all, and the returned array contains only a single, unbroken string element. If delimiter is the empty string or a regular expression that matches the empty string, the string is broken between each character, and the returned array has the same length as the string does, assuming no smaller limit is specified. (Note that this is a special case because the empty strings before the first character and after the last character are not matched.)

As noted earlier, the substrings in the array returned by this method do not contain the delimiting text used to split the string. However, if delimiter is a regular expression that contains parenthesized subexpressions, the substrings that match those parenthesized subexpressions (but not the text that matches the regular expression as a whole) are included in the returned array.

Note that the String.split( ) method is the inverse of the Array.join( ) method.

Example

The split( ) method is most useful when you are working with highly structured strings. For example:

"1:2:3:4:5".split(":");  // Returns ["1","2","3","4","5"]
"|a|b|c|".split("|");    // Returns ["", "a", "b", "c", ""]

Another common use of the split( ) method is to parse commands and similar strings by breaking them down into words delimited by spaces:

var words = sentence.split(' ');

It is easier to split a string into words using a regular expression as a delimiter:

var words = sentence.split(/\s+/);

To split a string into an array of characters, use the empty string as the delimiter. Use the limit argument if you only want to split a prefix of the string into an array of characters:

"hello".split("");     // Returns ["h","e","l","l","o"]
"hello".split("", 3);  // Returns ["h","e","l"]

If you want the delimiters or one or more portions of the delimiter included in the returned array, use a regular expression with parenthesized subexpressions. For example, the following code breaks a string at HTML tags and includes those tags in the returned array:

var text = "hello <b>world</b>";
text.split(/(<[^>]*>)/);  // Returns ["hello ","<b>","world","</b>",""]

Name

String.substr( ): extract a substring — JavaScript 1.2; deprecated

Synopsis

string.substr(start, length)

Arguments

start

The start position of the substring. If this argument is negative, it specifies a position measured from the end of the string: −1 specifies the last character, −2 specifies the second-to-last character, and so on.

length

The number of characters in the substring. If this argument is omitted, the returned substring includes all characters from the starting position to the end of the string.

Returns

A copy of the portion of string starting at and including the character specified by start and continuing for length characters, or to the end of the string if length is not specified.

Description

substr( ) extracts and returns a substring of string. It does not modify string.

Note that substr( ) specifies the desired substring with a character position and a length. This provides a useful alternative to String.substring( ) and String.splice( ), which specify a substring with two character positions. Note, however, that this method has not been standardized by ECMAScript and is therefore deprecated.

Example

var s = "abcdefg";
s.substr(2,2);   // Returns "cd"
s.substr(3);     // Returns "defg"
s.substr(-3,2);  // Should return "ef"; returns "ab" in IE 4

Bugs

Negative values for start do not work in IE. Instead of specifying a character position measured from the end of the string, they specify character position 0.

See Also

String.slice( ), String.substring( )

Name

String.substring( ): return a substring of a string — ECMAScript v1

Synopsis

string.substring(from, to)

Arguments

from

A nonnegative integer that specifies the position within string of the first character of the desired substring.

to

A nonnegative optional integer that is one greater than the position of the last character of the desired substring. If this argument is omitted, the returned substring runs to the end of the string.

Returns

A new string, of length to-from, which contains a substring of string. The new string contains characters copied from positions from to to−1 of string.

Description

String.substring( ) returns a substring of string consisting of the characters between positions from and to. The character at position from is included, but the character at position to is not included.

If from equals to, this method returns an empty (length 0) string. If from is greater than to, this method first swaps the two arguments and then returns the substring between them.

It is important to remember that the character at position from is included in the substring but that the character at position to is not included in the substring. While this may seem arbitrary or counterintuitive, a notable feature of this system is that the length of the returned substring is always equal to to-from.

Note that String.slice( ) and the nonstandard String.substr( ) can also extract substrings from a string. Unlike those methods, String.substring( ) does not accept negative arguments.

See Also

String.charAt( ), String.indexOf( ), String.lastIndexOf( ), String.slice( ), String.substr( )


Name

String.toLocaleLowerCase( ): convert a string to lowercase — ECMAScript v3

Synopsis

string.toLocaleLowerCase( )

Returns

A copy of string, converted to lowercase letters in a locale-specific way. Only a few languages, such as Turkish, have locale-specific case mappings, so this method usually returns the same value as toLowerCase( ).

See Also

String.toLocaleUpperCase( ), String.toLowerCase( ), String.toUpperCase( )


Name

String.toLocaleUpperCase( ): convert a string to uppercase — ECMAScript v3

Synopsis

string.toLocaleUpperCase( )

Returns

A copy of string, converted to uppercase letters in a locale-specific way. Only a few languages, such as Turkish, have locale-specific case mappings, so this method usually returns the same value as toUpperCase( ).

See Also

String.toLocaleLowerCase( ), String.toLowerCase( ), String.toUpperCase( )


Name

String.toLowerCase( ): convert a string to lowercase — ECMAScript v1

Synopsis

string.toLowerCase( )

Returns

A copy of string, with each uppercase letter converted to its lowercase equivalent, if it has one.


Name

String.toString( ): return the string — ECMAScript v1: Overrides Object.toString( )

Synopsis

string.toString( )

Returns

The primitive string value of string. It is rarely necessary to call this method.

Throws

TypeError

If this method is invoked on an object that is not a String.

See Also

String.valueOf( )

Name

String.toUpperCase( ): convert a string to uppercase — ECMAScript v1

Synopsis

string.toUpperCase( )

Returns

A copy of string, with each lowercase letter converted to its uppercase equivalent, if it has one.


Name

String.valueOf( ): return the string — ECMAScript v1: Overrides Object.valueOf( )

Synopsis

string.valueOf( )

Returns

The primitive string value of string.

Throws

TypeError

If this method is invoked on an object that is not a String.

See Also

String.toString( )

Name

SyntaxError: thrown to signal a syntax error — ECMAScript v3: Object → Error → SyntaxError

Constructor

new SyntaxError( )
new SyntaxError(message)

Arguments

message

An optional error message that provides details about the exception. If specified, this argument is used as the value for the message property of the SyntaxError object.

Returns

A newly constructed SyntaxError object. If the message argument is specified, the Error object uses it as the value of its message property; otherwise, it uses an implementation-defined default string as the value of that property. When the SyntaxError( ) constructor is called as a function, without the new operator, it behaves just as it does when called with the new operator.

Properties

message

An error message that provides details about the exception. This property holds the string passed to the constructor, or an implementation-defined default string. See Error.message for details.

name

A string that specifies the type of the exception. All SyntaxError objects inherit the value "SyntaxError" for this property.

Description

An instance of the SyntaxError class is thrown to signal a syntax error in JavaScript code. The eval( ) method, the Function( ) constructor, and the RegExp( ) constructor may all throw exceptions of this type. See Error for details about throwing and catching exceptions.

See Also

Error, Error.message, Error.name


Name

TypeError: thrown when a value is of the wrong type — ECMAScript v3: Object → Error → TypeError

Constructor

new TypeError( )
new TypeError(message)

Arguments

message

An optional error message that provides details about the exception. If specified, this argument is used as the value for the message property of the TypeError object.

Returns

A newly constructed TypeError object. If the message argument is specified, the Error object uses it as the value of its message property; otherwise, it uses an implementation-defined default string as the value of that property. When the TypeError( ) constructor is called as a function, without the new operator, it behaves just as it does when called with the new operator.

Properties

message

An error message that provides details about the exception. This property holds the string passed to the constructor, or an implementation-defined default string. See Error.message for details.

name

A string that specifies the type of the exception. All TypeError objects inherit the value "TypeError" for this property.

Description

An instance of the TypeError class is thrown when a value is not of the type expected. This happens most often when you attempt to access a property of a null or undefined value. It can also occur if you invoke a method defined by one class on an object that is an instance of some other class, or if you use the new operator with a value that is not a constructor function, for example. JavaScript implementations are also permitted to throw TypeError objects when a built-in function or method is called with more arguments than expected. See Error for details about throwing and catching exceptions.

See Also

Error, Error.message, Error.name


Name

undefined: the undefined value — ECMAScript v3

Synopsis

undefined

Description

undefined is a global property that holds the JavaScript undefined value. This is the same value that is returned when you attempt to read the value of a nonexistent object property. The undefined property is not enumerated by for/in loops and cannot be deleted with the delete operator. Note that undefined is not a constant and can be set to any other value, something that you should take care not to do.

When testing a value to see whether it is undefined, use the === operator, because the == operator treats the undefined value as equal to null.


Name

unescape( ): decode an escaped string — ECMAScript v1; deprecated in ECMAScript v3

Synopsis

unescape(s)

Arguments

s

The string that is to be decoded or "unescaped."

Returns

A decoded copy of s.

Description

unescape( ) is a global function that decodes a string encoded with escape( ). It decodes s by finding and replacing character sequences of the form % xx and %u xxxx (where x represents a hexadecimal digit) with the Unicode characters \u00 xx and \ u xxxx.

Although unescape( ) was standardized in the first version of ECMAScript, it has been deprecated and removed from the standard by ECMAScript v3. Implementations of ECMAScript are likely to implement this function, but they are not required to. You should use decodeURI( ) and decodeURIComponent( ) instead of unescape( ). See escape( ) for more details and an example.

See Also

decodeURI( ), decodeURIComponent( ), escape( ), String


Name

URIError: thrown by URI encoding and decoding methods — ECMAScript v3: Object → Error → URIError

Constructor

new URIError( )
new URIError(message)

Arguments

message

An optional error message that provides details about the exception. If specified, this argument is used as the value for the message property of the URIError object.

Returns

A newly constructed URIError object. If the message argument is specified, the Error object uses it as the value of its message property; otherwise, it uses an implementation-defined default string as the value of that property. When the URIError( ) constructor is called as a function without the new operator, it behaves just as it does when called with the new operator.

Properties

message

An error message that provides details about the exception. This property holds the string passed to the constructor, or an implementation-defined default string. See Error.message for details.

name

A string that specifies the type of the exception. All URIError objects inherit the value "URIError" for this property.

Description

An instance of the URIError class is thrown by decodeURI( ) and decodeURIComponent( ) if the specified string contains illegal hexadecimal escapes. It can also be thrown by encodeURI( ) and encodeURIComponent( ) if the specified string contains illegal Unicode surrogate pairs. See Error for details about throwing and catching exceptions.

See Also

Error, Error.message, Error.name

If you enjoyed this excerpt, buy a copy of JavaScript: The Definitive Guide.

Copyright © 2009 O'Reilly Media, Inc.