Book HomeMac OS X for Unix GeeksSearch this book

Chapter 23. Core JavaScript Reference

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

This reference section 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 a 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).

Sometimes you may find that you don't know the name of the class or interface that defines the method or property want to look up, or you may not be sure which of the three reference sections to look up a class or interface in. Part VI of this book is a special index designed to help with these situations. Look up the name of a class, method, or property, and it will tell you which reference section to look in and which class to look under in that section. For example, if you look up "Date," it will tell you that the Date class is documented in this core reference section. And if you look up the name "match," it will tell you that match( ) is a method of the String class and is also documented in this section.

Once you've found the reference 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 section 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.

Sample Entryhow to read core JavaScript reference pages

Title and Short Description

Every reference entry begins with a title block like that above. The entries are alphabetized by title. The short description, shown next to 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

This information tells you which version of Netscape's JavaScript interpreter and Microsoft's JScript interpreter the item (class, method, or property) was introduced in. If the item has been standardized in ECMAScript, it tells you which version of the standard introduced it. You can assume that anything available in one version of JavaScript is also available in later versions. Note, however, that if this section says the item is deprecated it may be removed in the future and you should avoid using it.

Inherits from/Overrides

If a class inherits from a superclass or a method overrides a method in a superclass, that information is shown in the "Inherits from/Overrides" section.

As described in Chapter 8, JavaScript classes can inherit properties and methods from other classes. For example, the String class inherits from Object, and the RangeError class inherits from Error, which in turn inherits from Object. 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, it usually has a "Constructor" section that 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. 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 simply represents an arbitrary value that is to be concatenated to the array. 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.

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 constructor, 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.

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 this core reference section, each property also has a complete reference page of its own. For example, the reference page for the Array class lists the length property in this section and gives a brief explanation of it, but the property is fully documented in the "Array.length" reference page. The property listing looks like this:

prop1
This is a summary of property prop1, including its type, its purpose or meaning, and whether it is read-only or read/write.

prop2
This is the same for prop2.

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.

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 in every version and implementation of JavaScript.

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.

arguments[ ]an array of function arguments

Availability

JavaScript 1.1; JScript 2.0; 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 7

Argumentsarguments and other properties of a function

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

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 were 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 were 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 7

Arguments.calleethe function that is currently running

Availability

JavaScript 1.2; JScript 5.5; 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
Arguments.lengththe number of arguments passed to a function

Availability

JavaScript 1.1; JScript 2; 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

Arraybuilt-in support for arrays

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

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 and JavaScript 1.2 and JScript 3.0 implement 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 concatenate them.

pop( )
Removes an item from the end of an array.

push( )
Pushes an item onto 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 9.

See Also

Chapter 9

Array.concat( )concatenate arrays

Availability

JavaScript 1.2; JScript 3.0; 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( )

Array.join( )concatenate array elements to form a string

Availability

JavaScript 1.1; JScript 2.0; 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 of the elements 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 up into array elements -- with the split( ) method of the String object. See the String.split( ) reference page 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( )

Array.lengththe size of an array

Availability

JavaScript 1.1, JScript 2.0; ECMAScript v1

Synopsis

array.length

Description

The length property of an array is always one larger than 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.

Array.pop( )remove and return the last element of an array

Availability

JavaScript 1.2; JScript 5.5; 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( )

Array.push( )append elements to an array

Availability

JavaScript 1.2; JScript 5.5; 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.

Bugs

In Netscape's implementations of JavaScript, when the language version is explicitly set to 1.2 this function returns the last value appended, rather than returning the new array length.

See Also

Array.pop( )

Array.reverse( )reverse the elements of an array

Availability

JavaScript 1.1; JScript 2.0; 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;
Array.shift( )shift array elements down

Availability

JavaScript 1.2; JScript 5.5; 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( )

Array.slice( )return a portion of an array

Availability

JavaScript 1.2; JScript 3.0; 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 second from 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 cannot be a negative number in Internet Explorer 4.

See Also

Array.splice( )

Array.sort( )sort the elements of an array

Availability

JavaScript 1.1; JScript 2.0; 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:

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
Array.splice( ) insert, remove, or replace array elements

Availability

JavaScript 1.2; JScript 5.5; 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. This argument is optional; if not specified, splice( ) deletes all elements from start to the end of the array.

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. Note, however, that due to a bug, the return value is not always an array in the Netscape implementation of JavaScript 1.2.

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(4);        // Returns [5,6,7,8]; a is [1,2,3,4]
a.splice(1,2);      // Returns [2,3]; a is [1,4]
a.splice(1,1);      // Netscape/JavaScript 1.2 returns 4 instead of [4]
a.splice(1,0,2,3);  // Netscape/JavaScript 1.2 returns undefined instead of []

Bugs

splice( ) is supposed to return an array of deleted elements in all cases. However, in Netscape's JavaScript 1.2 interpreter, when a single element is deleted it returns that element rather than an array containing the element. Also, if no elements are deleted, it returns nothing instead of returning an empty array. Netscape implementions of JavaScript emulate this buggy behavior whenever Version 1.2 of the language is explicitly specified.

See Also

Array.slice( )

Array.toLocaleString( )convert an array to a localized string

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v1

Inherits from/Overrides

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 toString( ) 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( )

Array.toString( )convert an array to a string

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

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 of the array elements to strings (by calling their toString( ) methods). Once each element is converted to a string, it 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.

Bugs

In Netscape implementations, when Version 1.2 of the language is explicitly specified, toString( ) returns its list of comma-and-space-separated array elements within square brackets using array literal notation. This occurs, for example, when the language attribute of a <script> tag is explicitly specified as "JavaScript1.2".

See Also

Array.toLocaleString( ), Object.toString( )

Array.unshift( )insert elements at the beginning of an array

Availability

JavaScript 1.2; JScript 5.5; ECMAScript v3

Synopsis

array.unshift(value, ...) 

Arguments

value, ...
One or more values that are to be 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( )

Booleansupport for boolean values

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

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 data type 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

Boolean.toString( )convert a boolean value to a string

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

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.

Boolean.valueOf( )the boolean value of a Boolean object

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

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.

Datemanipulate dates and times

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

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 UTC (similar to GMT) time. 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 would create 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 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 savings 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) of the date, using local or universal time.

set[UTC]Hours( )
Sets the hour (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 above, 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 data type built into the JavaScript language. Date objects are created with the new Date( ) syntax shown in the preceding Constructor section.

Once a Date object is created, there are a number of methods that allow you to operate on it. Most of the 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.

Example

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( )

Date.getDate( )return the day of the month

Availability

JavaScript 1.0; JScript 1.0; 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.

Date.getDay( )return the day of the week

Availability

JavaScript 1.0; JScript 1.0; 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).

Date.getFullYear( )return the year

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.getHours( )return the hours field of a Date

Availability

JavaScript 1.0; JScript 1.0; 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.).

Date.getMilliseconds( )return the milliseconds field of a Date

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v1

Synopsis

date.getMilliseconds( )

Returns

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

Date.getMinutes( )return the minutes field of a Date

Availability

JavaScript 1.0; JScript 1.0; 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.

Date.getMonth( )return the month of a Date

Availability

JavaScript 1.0; JScript 1.0; 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).

Date.getSeconds( )return the seconds field of a Date

Availability

JavaScript 1.0; JScript 1.0; 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.

Date.getTime( )return a Date in milliseconds

Availability

JavaScript 1.0; JScript 1.0; 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 millisecond representation without going through the overhead of first creating a Date object.

See Also

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

Date.getTimezoneOffset( )determine the offset from GMT

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

date.getTimezoneOffset( )

Returns

The difference, in minutes, between Greenwich Mean Time (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 savings 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.

Date.getUTCDate( )return the day of the month (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.getUTCDay( )return the day of the week (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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).

Date.getUTCFullYear( )return the year (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.getUTCHours( )return the hours field of a Date (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.).

Date.getUTCMilliseconds( )return the milliseconds field of a Date (universal time)

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v1

Synopsis

date.getUTCMilliseconds( )

Returns

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

Date.getUTCMinutes( )return the minutes field of a Date (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.getUTCMonth( )return the month of the year (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.getUTCSeconds( )return the seconds field of a Date (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.getYear( )return the year field of a Date

Availability

JavaScript 1.0; JScript 1.0; 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.

Bugs

Netscape implementations of JavaScript 1.0 through 1.2 subtract 1900 only for years between 1900 and 1999.

Date.parse( )parse a date/time string

Availability

JavaScript 1.0; JScript 1.0; 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( )

Date.setDate( )set the day of the month

Availability

JavaScript 1.0; JScript 1.0; 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-month field of date.

Returns

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

Date.setFullYear( )set the year and, optionally, the month and date

Availability

JavaScript 1.2; JScript 3.0; 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-month field of date.

Returns

The internal millisecond representation of the adjusted date.

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

Availability

JavaScript 1.0; JScript 1.0; 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.

Date.setMilliseconds( )set the milliseconds field of a Date

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.setMinutes( )set the minutes and seconds fields of a Date

Availability

JavaScript 1.0; JScript 1.0; 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.

Date.setMonth( )set the month and day fields of a Date

Availability

JavaScript 1.0; JScript 1.0; 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-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.

Date.setSeconds( )set the seconds and milliseconds fields of a Date

Availability

JavaScript 1.0; JScript 1.0; 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.

Date.setTime( )set a Date in milliseconds

Availability

JavaScript 1.0; JScript 1.0; 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.

Date.setUTCDate( )set the day of the month (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.setUTCFullYear( )set the year, month, and day (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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 be 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.

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

Returns

The internal millisecond representation of the adjusted date.

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

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.setUTCMilliseconds( )set the milliseconds field of a Date (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.setUTCMinutes( )set the minutes and seconds fields of a Date (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.setUTCMonth( )set the month and day fields of a Date (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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-month field of date.

Returns

The millisecond representation of the adjusted date.

Date.setUTCSeconds( )set the seconds and milliseconds fields of a Date (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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.

Date.setYear( )set the year field of a Date

Availability

JavaScript 1.0; JScript 1.0; 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.

Date.toDateString( )return the date portion of a Date as a string

Availability

JavaScript 1.5; JScript 5.5; 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( )

Date.toGMTString( )convert a Date to a universal time string

Availability

JavaScript 1.0; JScript 1.0; 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( )

Date.toLocaleDateString( )return the date portion of a Date as a locally formatted string

Availability

JavaScript 1.5; JScript 5.5; 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( )

Date.toLocaleString( )convert a Date to a locally formatted string

Availability

JavaScript 1.0; JScript 1.0; 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( )

Date.toLocaleTimeString( )return the time portion of a Date as a locally formatted string

Availability

JavaScript 1.5; JScript 5.5; 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( )

Date.toString( )convert a Date to a string

Availability

JavaScript 1.0; JScript 1.0; 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( )

Date.toTimeString( )return the time portion of a Date as a string

Availability

JavaScript 1.5; JScript 5.5; 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( )

Date.toUTCString( )convert a Date to a string (universal time)

Availability

JavaScript 1.2; JScript 3.0; 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( )

Date.UTC( )convert a Date specification to milliseconds

Availability

JavaScript 1.0; JScript 1.0; 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 will be added to it and it will be 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. 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 (Universal Coordinated Time) -- 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( )

Date.valueOf( )convert a Date to millisecond representation

Availability

JavaScript 1.1; ECMAScript v1

Inherits from/Overrides

Overrides Object.valueOf( )

Synopsis

date.valueOf( )

Returns

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

decodeURI( )unescape characters in a URI

Availability

JavaScript 1.5; JScript 5.5; 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 for details.

See Also

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

decodeURIComponent( )unescape characters in a URI component

Availability

JavaScript 1.5; JScript 5.5; 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( )

encodeURI( )escape characters in a URI

Availability

JavaScript 1.5; JScript 5.5; 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 the 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 may 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( )

encodeURIComponent( )escape characters in a URI component

Availability

JavaScript 1.5; JScript 5.5; 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 /, :, # 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( )

Errora generic exception

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Inherits from/Overrides

Inherits from Object

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 will use it as the value of its message property; otherwise, it will use 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 be used to provide human-readable details about the exception.

The JavaScript interpreter never throws Error object 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 convert 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.

Example

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

Error.messagea human-readable error message

Availability

JavaScript 1.5; JScript 5.5; 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.

Error.namethe type of an error

Availability

JavaScript 1.5; JScript 5.5; 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".

Error.toString( )convert an Error object to a string

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Inherits from/Overrides

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.

escape( )encode a string

Availability

JavaScript 1.0; JScript 1.0; 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 %uxxxx (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 %uxxxx sequence.

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

In client-side JavaScript, a common use of escape( ) is to encode cookie values, which have restrictions on the punctuation characters they may contain. See the Document.cookie reference page in the client-side reference section.

Although the escape( ) function 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. In JavaScript 1.5 and JScript 5.5 and later, you should use encodeURI( ) and encodeURIComponent( ) instead of escape( ).

Example

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

See Also

encodeURI( ), encodeURIComponent( ), String, escape( ); Document.cookie in the client-side reference section

eval( )execute JavaScript code from a string

Availability

JavaScript 1.0; JScript 1.0; 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 below.

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

Description

eval( ) is a global method that evaluates a string containing JavaScript code. 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
EvalErrorthrown when eval( ) is used improperly

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Inherits from/Overrides

Inherits from Error

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 will use it as the value of its message property; otherwise, it will use 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

Functiona JavaScript function

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

Synopsis

function functionname(argument_name_list) // Function definition statement 
{
    body 
} 
function (argument_name_list) { body } // Unnamed function literal; JavaScript 1.2 
functionname(argument_value_list)      // Function invocation

Constructor

new Function(argument_names..., body) // JavaScript 1.1 and later

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 data type in JavaScript. Chapter 7 explains how to define and use functions, and Chapter 8 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 above. See the Arguments reference page for details.

See Also

Arguments; Chapter 7; Chapter 8

Function.apply( )invoke a function as a method of an object

Availability

JavaScript 1.2; JScript 5.5; 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.

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( )

Function.arguments[]arguments passed to a function

Availability

JavaScript 1.0; JScript 1.0; 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 only defined 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

Function.call( )invoke a function as a method of an object

Availability

JavaScript 1.5; JScript 5.5; 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.

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.

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( )

Function.callerthe function that called this one

Availability

JavaScript 1.0, JScript 2.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 was invoked from the top level of a JavaScript program, caller is null. This property may only be used 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.

Function.lengththe number of declared arguments

Availability

JavaScript 1.1; JScript 2.0; 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

Function.prototypethe prototype for a class of objects

Availability

JavaScript 1.1; JScript 2.0; 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 8 for a full discussion of constructor functions, the prototype property, and the definition of classes in JavaScript.

Bugs

JavaScript 1.1 requires a constructor to be used once before anything can be assigned to its prototype object.

See Also

Chapter 8

Function.toString( )convert a function to a string

Availability

JavaScript 1.0; JScript 2.0; 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 Netscape implementations, 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.

Globalthe global object

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

this 

Global Properties

The global object is not a class, so the following global properties have individual reference entries under their own name. 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.

NaN
The not-a-number value.

undefined
The undefined value.

Global Functions

The global object is an object, not a class. The global functions listed below 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 return the result.

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 above, the global object also defines properties that refer to all the other predefined JavaScript objects. All of 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. In client-side JavaScript, for example, 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";

See Also

Window in the client-side reference section; Chapter 4

Infinitya numeric property that represents infinity

Availability

JavaScript 1.3; JScript 3.0; 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

isFinite( )determine whether a number is finite

Availability

JavaScript 1.2; JScript 3.0; 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

isNaN( )check for not-a-number

Availability

JavaScript 1.1; JScript 1.0; 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( )

Mathmathematical functions and constants

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.constant 
Math.function( )

Constants

Math.E
The constant e the base of the natural logarithms.

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 Figure .

Math.SQRT1_2
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 arc cosine.

Math.asin( )
Computes an arc sine.

Math.atan( )
Computes an arc tangent.

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 an exponent 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 xy

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 conveniently grouped by this Math object and are invoked with syntax like this:

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

Math is not a class of objects like 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

Math.abs( )compute an absolute value

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.abs(x) 

Arguments

x
Any number.

Returns

The absolute value of x.

Math.acos( )compute an arc cosine

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.acos(x)

Arguments

x
A number between -1.0 and 1.0.

Returns

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

Math.asin( )compute an arc sine

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.asin(x)

Arguments

x
A number between -1.0 and 1.0.

Returns

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

Math.atan( )compute an arc tangent

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.atan(x)

Arguments

x
Any number.

Returns

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

Math.atan2( )compute the angle from the X-axis to a point

Availability

JavaScript 1.0; JScript 1.0; 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 -Figure and Figure 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.

Math.ceil( )round a number up

Availability

JavaScript 1.0; JScript 1.0; 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 
Math.cos( )compute a cosine

Availability

JavaScript 1.0; JScript 1.0; 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 (2Figure /360).

Returns

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

Math.Ethe mathematical constant e

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.E

Description

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

Math.exp( )compute ex

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.exp(x)

Arguments

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

Returns

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

Math.floor( )round a number down

Availability

JavaScript 1.0; JScript 1.0; 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 
Math.LN10the mathematical constant loge10

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.LN10

Description

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

Math.LN2the mathematical constant loge2

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.LN2

Description

Math.LN2 is loge2 the natural logarithm of 2. This constant has a value of approximately 0.69314718055994528623.

Math.log( )compute a natural logarithm

Availability

JavaScript 1.0; JScript 1.0; 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 log3x 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); } 
Math.LOG10Ethe mathematical constant log10e

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.LOG10E

Description

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

Math.LOG2Ethe mathematical constant log2e

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.LOG2E 

Description

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

Math.max( )return the largest argument

Availability

JavaScript 1.0; JScript 1.0; 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 non-numeric value that cannot be converted to a number.

Math.min( )return the smallest argument

Availability

JavaScript 1.0; JScript 1.0; 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 non-numeric value that cannot be converted to a number.

Math.PIthe mathematical constant

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.PI

Description

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

Math.pow( )compute xy

Availability

JavaScript 1.0; JScript 1.0; 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, xy.

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.

Math.random( )return a pseudorandom number

Availability

JavaScript 1.1; JScript 1.0; ECMAScript v1

Synopsis

Math.random( )

Returns

A pseudorandom number between 0.0 and 1.0.

Math.round( )round to the nearest integer

Availability

JavaScript 1.0; JScript 1.0; 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.

Math.sin( )compute a sine

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.sin(x)

Arguments

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

Returns

The sine of x.

Math.sqrt( )compute a square root

Availability

JavaScript 1.0; JScript 1.0; 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
Math.SQRT1_2the mathematical constant 1/

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.SQRT1_2

Description

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

Math.SQRT2the mathematical constant

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Synopsis

Math.SQRT2

Description

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

Math.tan( )compute a tangent

Availability

JavaScript 1.0; JScript 1.0; 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 (2Figure /360).

Returns

The tangent of the specified angle x.

NaNthe not-a-number property

Availability

JavaScript 1.3; JScript 3.0; ECMAScript v1

Synopsis

NaN 

Description

NaN is 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( ), since NaN always compares non-equal to any other value, including itself!

See Also

Infinity, isNaN( ), Number.NaN

Numbersupport for numbersNumber object

Availability

JavaScript 1.1; JScript 2.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

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.

Description

Numbers are a basic, primitive data type in JavaScript. In JavaScript 1.1, however, 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. In JavaScript 1.1, 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 not-a-number 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 we 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

Number.MAX_VALUEthe maximum numeric value

Availability

JavaScript 1.1; JScript 2.0, ECMAScript v1

Synopsis

Number.MAX_VALUE

Description

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

Number.MIN_VALUEthe minimum numeric value

Availability

JavaScript 1.1; JScript 2.0, 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.

Number.NaNthe special not-a-number value

Availability

JavaScript 1.1; JScript 2.0, 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 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 constant NaN instead of using Number.NaN.

See Also

isNaN( ), NaN

Number.NEGATIVE_INFINITYnegative infinity

Availability

JavaScript 1.1; JScript 2.0, 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( )

Number.POSITIVE_INFINITYinfinity

Availability

JavaScript 1.1; JScript 2.0, 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 constant Infinity instead of Number.POSITIVE_INFINITY.

See Also

Infinity, isFinite( )

Number.toExponential( )format a number using exponential notation

Availability

JavaScript 1.5; JScript 5.5, ECMAScript v3

Synopsis

number.toExponential(digits)

Arguments

digits
The number of digits that will 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, as many digits as necessary will be 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( )

Number.toFixed( )format a number using fixed-point notation

Availability

JavaScript 1.5; JScript 5.5, 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( )

Number.toLocaleString( )convert a number to a locally formatted string

Availability

JavaScript 1.5; JScript 5.5, 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( )

Number.toPrecision( )format the significant digits of a number

Availability

JavaScript 1.5; JScript 5.5, 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( )

Number.toString( )convert a number to a string

Availability

JavaScript 1.1; JScript 2.0, ECMAScript v1

Inherits from/Overrides

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.

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. If radix is any other value, this method returns an implementation-defined string. Netscape implementations and Microsoft implementations after JScript 3.0 honor the radix argument and return a string representation of the number in the specified base.

See Also

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

Number.valueOf( )return the primitive number value

Availability

JavaScript 1.1; JScript 2.0, ECMAScript v1

Inherits from/Overrides

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( )

Objecta superclass that contains features of all

Availability

JavaScript objectsJavaScript 1.0; JScript 1.0; 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. This object is not supported prior to JavaScript 1.1 and ECMAScript v1.

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 data type 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 8.

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

See Also

Array, Boolean, Function, Function.prototype, Number, String; Chapter 8

Object.constructoran object's constructor function

Availability

JavaScript 1.1; JScript 2.0; 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-in to 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( )

Object.hasOwnProperty( )check whether a property is inherited

Availability

JavaScript 1.5; JScript 5.5; 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. Returns 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 8, 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 8

Object.isPrototypeOf( )is one object the prototype of another?

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Synopsis

object.isPrototypeOf(o)

Arguments

o
Any object.

Returns

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

Description

As explained in Chapter 8, JavaScript objects inherit properties from their prototype object. The prototype of an object is referred to by the prototype property of the constructor function used to create and initialize 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 8

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

Availability

JavaScript 1.5; JScript 5.5; 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 that it only works 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

Bugs

The specification is apparently in error when it restricts propertyIsEnumerable( ) to check only noninherited properties. Internet Explorer 5.5 implements this method as specified. Netscape 6.0 implements it so that it does consider the prototype chain. Although this is the way the method was probably intended to work, it violates the specification, and Netscape 6.1 has been modified to match the IE 5.5. Because of the error in the specification, this method is less useful than it should be.

See Also

Function.prototype, Object.hasOwnProperty( ); Chapter 8

Object.toLocaleString( )return an object's localized string representation

Availability

JavaScript 1.5; JScript 5.5; 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( )

Object.toString( )define an object's string representation

Availability

JavaScript 1.0; JScript 2.0; 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, if 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:

[object class] 

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 that you can use to force a conversion.

In other circumstances, you might choose to use a toString( ) call even in a context where JavaScript would do 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( )

Object.valueOf( )the primitive value of the specified object

Availability

JavaScript 1.1; JScript 2.0; 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. But you might also want the ability 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 could then do things like pass one of your complex number objects to Math.sqrt( ), which would compute the square root of the real portion of the complex number.

See Also

Object.toString( )

parseFloat( )convert a string to a number

Availability

JavaScript 1.0; JScript 1.0; 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 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( ).

Bugs

NaN is not supported in JavaScript 1.0, so in that version of the language, parseFloat( ) returns 0 when it cannot parse s. This means that in JavaScript 1.0, if the return value of parseFloat( ) is 0, you must perform additional tests on s to determine whether it really represents the number zero or does not represent a number at all.

See Also

isNaN( ), parseInt( )

parseInt( )convert a string to an integer

Availability

JavaScript 1.0; JScript 1.1; 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 the 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 or hexadecimal numbers with the "0x" or "0X" prefix.

In JavaScript 1.0, NaN is not supported, and parseInt( ) returns 0 instead of NaN when it cannot parse s. In this version of the language, parseInt( ) cannot distinguish between malformed input and a the legal input "0".

See Also

isNaN( ), parseFloat( )

RangeErrorthrown when a number is out of its legal rangeRangeError object errorsRangeError object

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3 Inherits from Error

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 will use it as the value of its message property; otherwise, it will use 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 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 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 is set 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

ReferenceErrorthrown when reading a variable that does not exist ReferenceError object errorsReferenceError object

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Inherits from/Overrides

Inherits from Error

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 will use it as the value of its message property; otherwise, it will use 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 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 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

RegExpregular expressions for pattern matching RegExp object pattern matching (and regular expressions)RegExp object

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v3

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. 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 10 for complete details on regular expression syntax and use.

See Also

Chapter 10

RegExp.exec( )general-purpose pattern matching

Availability

JavaScript 1.2; JScript 3.0; 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 above. 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);
}

Bugs

In JScript 3.0, exec( ) does not properly set or use the lastIndex property, so it cannot be used with global patterns in the kind of loop shown in the example above.

See Also

RegExp.lastIndex, RegExp.test( ), String.match( ), String.replace( ), String.search( ); Chapter 10

RegExp.globalwhether a regular expression matches globally global property g attribute (global matching)

Availability

JavaScript 1.2; JScript 5.5; 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.

RegExp.ignoreCasewhether a regular expression is case-insensitive ignoreCase property caseinsensitivity toin pattern matching i attribute (case-insensitive matching)

Availability

JavaScript 1.2; JScript 5.5; 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.

RegExp.lastIndexthe starting position of the next match

Availability

JavaScript 1.2; JScript 5.5; 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 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( )

RegExp.sourcethe text of the regular expression

Availability

JavaScript 1.2; JScript 3.0; 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.

RegExp.test( )test whether a string matches a patterntest() method

Availability

JavaScript 1.2; JScript 3.0; 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 10

RegExp.toString( )convert a regular expression to a string

Availability

JavaScript 1.2; JScript 3.0; ECMAScript v3

Inherits from/Overrides

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, or it could also add an escape sequence and return /\//g.

Stringsupport for stringsString object

Availability

JavaScript 1.0; JScript 1.0; ECMAScript v1

Inherits from/Overrides

Inherits from Object

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.

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.

substring( )
Extracts a substring of a string.

substr( )
Extracts a substring of a string. A variant of substring( ).

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 JavaScript 1.0 and JScript 1.0, 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-side 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 a <i> environment.

link(url)
Returns a copy of the string, in a <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> environment.

sup( )
Returns a copy of the string, in a <sup> environment.

Description

Strings are a primitive data type 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: there are methods for extracting a character or a substring from the string or searching for a character or a substring, for example. 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 like String.toUpperCase( ) return an entirely new string, without modifying the original.

In Netscape implementations of JavaScript 1.2 and later, strings behave like read-only arrays of characters. For example, to extract the 3rd character from a string s, you could 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 of Netscape's implementations is not standard, you should usually avoid using it.

See Also

Chapter 3

String.charAt( )get the nth character from a string

Availability

JavaScript 1.0; JScript 1.0, 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( )

String.charCodeAt( )get the nth character code from a string

Availability

JavaScript 1.2; JScript 5.5; 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.

Bugs

JavaScript 1.2 (as implemented by Netscape 4.0, for example) does not have full support for 16-bit Unicode characters and strings.

See Also

String.charAt( ), String.fromCharCode( )

String.concat( )concatenate strings

Availability

JavaScript 1.2; JScript 3.0; 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( )

String.fromCharCode( )create a string from character encodings

Availability

JavaScript 1.2; JScript 3.0; 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);

Bugs

JavaScript 1.2 (as implemented by Netscape 4.0, for example) does not have full support for 16-bit Unicode characters and strings.

See Also

String.charCodeAt( )

String.indexOf( )search a stringindexOf() method

Availability

JavaScript 1.0; JScript 1.0, 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.

Bugs

In JavaScript 1.0 and 1.1, if start is greater than the length of string, indexOf( ) returns the empty string, rather than -1.

See Also

String.charAt( ), String.lastIndexOf( ), String.substring( )

String.lastIndexOf( )search a string backwardlastIndexOf() method

Availability

JavaScript 1.0; JScript 1.0, ECMAScript v1

Synopsis

string.lastIndexOf(substring) 
string.lastIndexOf(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 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( )

String.lengththe length of a string

Availability

JavaScript 1.0; JScript 1.0, 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.

String.localeCompare( )compare one string to another, using locale-specific ordering

Availability

JavaScript 1.5; JScript 5.5; 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 utilizes 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) });
String.match( )find one or more regular expression matches

Availability

JavaScript 1.2; JScript 3.0; 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 below.

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 10 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 matched 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 10

String.replace( )replace substring(s) matching a regular expressionreplace() methodString object regular expressionsreplacing substrings that match pattern matching (and regular expressions)substring matches, replacing

Availability

JavaScript 1.2; JScript 3.0; 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 Section 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. Except, however, 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 to be 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, and this feature is implemented in JavaScript 1.2 and JScript 5.5. 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 matched the pattern. The next arguments are the strings that matched 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 10

String.search( )search for a regular expression search() methodString object regular expressionsstrings, searching for matches pattern matching (and regular expressions)strings, searching for matches

Availability

JavaScript 1.2; JScript 3.0; 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 was 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 10

String.slice( )extract a substring slice() methodString object

Availability

JavaScript 1.2; JScript 3.0; 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 JScript 3.0 (Internet Explorer 4). Instead of specifying a character position measured from the end of the string, they specify character position 0.

See Also

Array.slice( ), String.substring( )

String.split( )break a string into an array of stringssplit() methodString object

Availability

JavaScript 1.1; JScript 3.0; ECMAScript v1; enhanced in ECMAScript v3

Synopsis

string.split(delimiter, limit)

Arguments

delimiter
The string or regular expression at which the string splits. The use of a regular expression as a delimiter is standardized by ECMAScript v3 and implemented in JavaScript 1.2 and JScript 3.0; it is not implemented in JavaScript 1.1.

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. This argument is standardized by ECMAScript v3 and implemented in JavaScript 1.2 and JScript 3.0; it is not implemented in JavaScript 1.1.

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 below.

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 below. 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 since the empty string before the first character and after the last character is not matched.)

We said above that 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(' '); 

See the Section section for details on a special case when delimiter is a single space. 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>",""] 

Bugs

In Netscape's implementations of JavaScript, when language Version 1.2 is explicitly requested (with the language attribute of a <script> tag, for example), the split( ) method has one special-case behavior: if delimiter is a single space, the method splits the string at spaces but ignores any white space at the beginning and end of the string. See Section 11.6, for further details.

See Also

Array.join( ), RegExp; Chapter 10

String.substr( )extract a substring

Availability

JavaScript 1.2; JScript 3.0; 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 JScript 3.0 (IE 4). Instead of specifying a character position measured from the end of the string, they specify character position 0.

See Also

String.slice( ), String.substring( )

String.substring( )return a substring of a string

Availability

JavaScript 1.0; JScript 1.0, ECMAScript v1

Synopsis

string.substring(from, to)

Arguments

from
An integer that specifies the position within string of the first character of the desired substring.

to
An 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 be used to extract substrings from a string.

Bugs

In Netscape's implementations of JavaScript, when language Version 1.2 is explicitly requested (with the language attribute of a <script> tag, for example), this method does not correctly swap its arguments if from is greater than to. Instead it returns the empty string.

See Also

String.charAt( ), String.indexOf( ), String.lastIndexOf( ), String.slice( ), String.substr( )

String.toLocaleLowerCase( )convert a string to lowercase

Availability

JavaScript 1.5; JScript 5.5, 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( )

String.toLocaleUpperCase( )convert a string to uppercase

Availability

JavaScript 1.5; JScript 5.5, 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( )

String.toLowerCase( )convert a string to lowercase

Availability

JavaScript 1.0; JScript 1.0, ECMAScript v1

Synopsis

string.toLowerCase( )

Returns

A copy of string, with each uppercase letter converted to its lowercase equivalent, if it has one.

String.toString( )return the stringtoString() methodString object

Availability

JavaScript 1.0; JScript 1.0, 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( )

String.toUpperCase( )convert a string to uppercase

Availability

JavaScript 1.0; JScript 1.0, ECMAScript v1

Synopsis

string.toUpperCase( )

Returns

A copy of string, with each lowercase letter converted to its uppercase equivalent, if it has one.

String.valueOf( )return the string

Availability

JavaScript 1.0; JScript 1.0, 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( )

SyntaxErrorthrown to signal a syntax error SyntaxError object errorsSyntaxError object

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3

Inherits from/Overrides

Inherits from Error

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 will use it as the value of its message property; otherwise, it will use 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

TypeErrorthrown when a value is of the wrong type TypeError object errorsTypeError object data typesTypeError exceptions

Availability

JavaScript 1.5; JScript 5.5; ECMAScript

Inherits from/Overrides

v3 Inherits from Error

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 will use it as the value of its message property; otherwise, it will use 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

undefinedthe undefined value

Availability

JavaScript 1.5; JScript 5.5; 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.

unescape( )decode an escaped string

Availability

JavaScript 1.0; JScript 1.0; 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 %uxxxx (where x represents a hexadecimal digit) with the Unicode characters \u00xx and \uxxxx.

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. In JavaScript 1.5 and JScript 5.5 and later, you should use decodeURI( ) and decodeURIComponent( ) instead of unescape( ). See escape( ) for more details and an example.

See Also

decodeURI( ), decodeURIComponent( ), escape( ), String

URIErrorthrown by URI encoding and decoding methods URIError object errorsURIError object

Availability

JavaScript 1.5; JScript 5.5; ECMAScript v3 Inherits from Error

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 will use it as the value of its message property; otherwise, it will use 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



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.