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 Entry | how to read core JavaScript reference pages |
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.
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.
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.
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.
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.
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.
If a constructor, function, or method has a return value, this subsection explains that value.
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.
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:
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.
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.
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.
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.
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 |
JavaScript 1.1; JScript 2.0; ECMAScript v1
arguments
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.
Arguments | arguments and other properties of a function |
JavaScript 1.1; JScript 2.0; ECMAScript v1
Inherits from Object
arguments arguments[n]
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.
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.
Arguments.callee | the function that is currently running |
JavaScript 1.2; JScript 5.5; ECMAScript v1
arguments.callee
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.
// 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.length | the number of arguments passed to a function |
JavaScript 1.1; JScript 2; ECMAScript v1
arguments.length
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.
// 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 }
Array | built-in support for arrays |
JavaScript 1.1; JScript 2.0; ECMAScript v1
Inherits from Object
new Array( ) new Array(size) new Array(element0, element1, ..., elementn)
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.
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)];
Arrays are a basic feature of JavaScript and are documented in detail in Chapter 9.
Array.concat( ) | concatenate arrays |
JavaScript 1.2; JScript 3.0; ECMAScript v3
array.concat(value, ...)
A new array, which is formed by concatenating each of the specified arguments to array.
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.
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]]
Array.join( ) | concatenate array elements to form a string |
JavaScript 1.1; JScript 2.0; ECMAScript v1
array.join( ) array.join(separator)
The string that results from converting each element of array to a string and then concatenating them together, with the separator string between elements.
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.
a = new Array(1, 2, 3, "testing"); s = a.join("+"); // s is the string "1+2+3+testing"
Array.length | the size of an array |
JavaScript 1.1, JScript 2.0; ECMAScript v1
array.length
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 |
JavaScript 1.2; JScript 5.5; ECMAScript v3
array.pop( )
The last element of array.
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.
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
Array.push( ) | append elements to an array |
JavaScript 1.2; JScript 5.5; ECMAScript v3
array.push(value, ...)
The new length of the array, after the specified values are appended to it.
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.
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.
Array.reverse( ) | reverse the elements of an array |
JavaScript 1.1; JScript 2.0; ECMAScript v1
array.reverse( )
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.
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 |
JavaScript 1.2; JScript 5.5; ECMAScript v3
array.shift( )
The former first element of the array.
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( ).
var a = [1, [2,3], 4] a.shift( ); // Returns 1; a = [[2,3], 4] a.shift( ); // Returns [2,3]; a = [4]
Array.slice( ) | return a portion of an array |
JavaScript 1.2; JScript 3.0; ECMAScript v3
array.slice(start, end)
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.
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( ).
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]
start cannot be a negative number in Internet Explorer 4.
Array.sort( ) | sort the elements of an array |
JavaScript 1.1; JScript 2.0; ECMAScript v1
array.sort( ) array.sort(orderfunc)
A reference to the array. Note that the array is sorted in place and no copy is made.
The sort( ) method sorts the elements of array in place -- no copy of the array is made. If sort( ) is called with no arguments, the elements of the array are arranged in alphabetical order (more precisely, the order determined by the character encoding). To do this, elements are first converted to strings, if necessary, so that they can be compared.
If you want to sort the array elements in some other order, you must supply a comparison function that compares two values and returns a number indicating their relative order. The comparison function should take two arguments, a and b, and should return one of the following:
A value less than zero, if, according to your sort criteria, a is "less than" b and should appear before b in the sorted array.
Zero, if a and b are equivalent for the purposes of this sort.
A value greater than zero, if a is "greater than" b for the purposes of the sort.
Note that undefined elements of an array are always sorted to the end of the array. This is true even if you provide a custom ordering function: undefined values are never passed to the orderfunc you supply.
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 |
JavaScript 1.2; JScript 5.5; ECMAScript v3
array.splice(start, deleteCount, value, ...)
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.
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.
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 []
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.
Array.toLocaleString( ) | convert an array to a localized string |
JavaScript 1.5; JScript 5.5; ECMAScript v1
Overrides Object.toLocaleString( )
array.toLocaleString( )
A localized string representation of array.
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.
Array.toString( ) | convert an array to a string |
JavaScript 1.1; JScript 2.0; ECMAScript v1
Overrides Object.toString( )
array.toString( )
A string representation of array.
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.
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".
Array.unshift( ) | insert elements at the beginning of an array |
JavaScript 1.2; JScript 5.5; ECMAScript v3
array.unshift(value, ...)
The new length of the array.
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.
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
Boolean | support for boolean values |
JavaScript 1.1; JScript 2.0; ECMAScript v1
Inherits from Object
new Boolean(value) //Constructor function Boolean(value) // Conversion function
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.
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.
Boolean.toString( ) | convert a boolean value to a string |
JavaScript 1.1; JScript 2.0; ECMAScript v1
Overrides Object.toString( )
b.toString( )
The string "true" or "false", depending on the value of the primitive boolean value or Boolean object b.
Boolean.valueOf( ) | the boolean value of a Boolean object |
JavaScript 1.1; JScript 2.0; ECMAScript v1
Overrides Object.valueOf( )
b.valueOf( )
The primitive boolean value held by the Boolean object b.
Date | manipulate dates and times |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Inherits from Object
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.
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.
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:
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.
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>
Date.getDate( ) | return the day of the month |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.getDate( )
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.getDay( )
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 |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getFullYear( )
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.getHours( )
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 |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getMilliseconds( )
The milliseconds field, expressed in local time, of date.
Date.getMinutes( ) | return the minutes field of a Date |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.getMinutes( )
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.getMonth( )
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.getSeconds( )
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.getTime( )
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.
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.
Date.getTimezoneOffset( ) | determine the offset from GMT |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.getTimezoneOffset( )
The difference, in minutes, between Greenwich Mean Time (GMT) and local time.
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) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getUTCDate( )
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) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getUTCDay( )
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) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getUTCFullYear( )
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) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getUTCHours( )
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) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getUTCMilliseconds( )
The milliseconds field, expressed in universal time, of date.
Date.getUTCMinutes( ) | return the minutes field of a Date (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getUTCMinutes( )
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) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getUTCMonth( )
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) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.getUTCSeconds( )
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1; deprecated by ECMAScript v3
date.getYear( )
The year field of the specified Date object date minus 1900.
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.
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Date.parse(date)
The number of milliseconds between the specified date and time and midnight GMT on January 1, 1970.
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.
Date.setDate( ) | set the day of the month |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.setDate(day_of_month)
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 |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setFullYear(year) date.setFullYear(year, month) date.setFullYear(year, month, day)
The internal millisecond representation of the adjusted date.
Date.setHours( ) | set the hours, minutes, seconds, and milliseconds fields of a Date |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.setHours(hours) date.setHours(hours, minutes) date.setHours(hours, minutes, seconds) date.setHours(hours, minutes, seconds, millis)
The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.
Date.setMilliseconds( ) | set the milliseconds field of a Date |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setMilliseconds(millis)
The millisecond representation of the adjusted date.
Date.setMinutes( ) | set the minutes and seconds fields of a Date |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.setMinutes(minutes) date.setMinutes(minutes, seconds) date.setMinutes(minutes, seconds, millis)
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.setMonth(month) date.setMonth(month, day)
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.setSeconds(seconds) date.setSeconds(seconds, millis)
The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.
Date.setTime( ) | set a Date in milliseconds |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.setTime(milliseconds)
The milliseconds argument. Prior to ECMAScript standardization, this method returns nothing.
Date.setUTCDate( ) | set the day of the month (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setUTCDate(day_of_month)
The internal millisecond representation of the adjusted date.
Date.setUTCFullYear( ) | set the year, month, and day (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setUTCFullYear(year) date.setUTCFullYear(year, month) date.setUTCFullYear(year, month, day)
The internal millisecond representation of the adjusted date.
Date.setUTCHours( ) | set the hours, minutes, seconds, and milliseconds fields of a Date (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setUTCHours(hours) date.setUTCHours(hours, minutes) date.setUTCHours(hours, minutes, seconds) date.setUTCHours(hours,minutes, seconds, millis)
The millisecond representation of the adjusted date.
Date.setUTCMilliseconds( ) | set the milliseconds field of a Date (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setUTCMilliseconds(millis)
The millisecond representation of the adjusted date.
Date.setUTCMinutes( ) | set the minutes and seconds fields of a Date (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setUTCMinutes(minutes) date.setUTCMinutes(minutes, seconds) date.setUTCMinutes(minutes, seconds, millis)
The millisecond representation of the adjusted date.
Date.setUTCMonth( ) | set the month and day fields of a Date (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setUTCMonth(month) date.setUTCMonth(month, day)
The millisecond representation of the adjusted date.
Date.setUTCSeconds( ) | set the seconds and milliseconds fields of a Date (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.setUTCSeconds(seconds) date.setUTCSeconds(seconds, millis)
The millisecond representation of the adjusted date.
Date.setYear( ) | set the year field of a Date |
JavaScript 1.0; JScript 1.0; ECMAScript v1; deprecated by ECMAScript v3
date.setYear(year)
The millisecond representation of the adjusted date. Prior to ECMAScript standardization, this method returns nothing.
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 |
JavaScript 1.5; JScript 5.5; ECMAScript v3
date.toDateString( )
An implementation-dependent human-readable string representation of the date portion of date, expressed in the local time zone.
Date.toLocaleDateString( ), Date.toLocaleString( ), Date.toLocaleTimeString( ), Date.toString( ), Date.toTimeString( )
Date.toGMTString( ) | convert a Date to a universal time string |
JavaScript 1.0; JScript 1.0; ECMAScript v1; deprecated by ECMAScript v3
date.toGMTString( )
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.
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.
Date.toLocaleDateString( ) | return the date portion of a Date as a locally formatted string |
JavaScript 1.5; JScript 5.5; ECMAScript v3
date.toLocaleDateString( )
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.
Date.toDateString( ), Date.toLocaleString( ), Date.toLocaleTimeString( ), Date.toString( ), Date.toTimeString( )
Date.toLocaleString( ) | convert a Date to a locally formatted string |
JavaScript 1.0; JScript 1.0; ECMAScript v1
date.toLocaleString( )
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.
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.
Date.toLocaleDateString( ), Date.toLocaleTimeString( ), Date.toString( ), Date.toUTCString( )
Date.toLocaleTimeString( ) | return the time portion of a Date as a locally formatted string |
JavaScript 1.5; JScript 5.5; ECMAScript v3
date.toLocaleTimeString( )
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.
Date.toDateString( ), Date.toLocaleDateString( ), Date.toLocaleString( ), Date.toString( ), Date.toTimeString( )
Date.toString( ) | convert a Date to a string |
JavaScript 1.0; JScript 1.0; ECMAScript v1 Overrides Object.toString( )
date.toString( )
A human-readable string representation of date, expressed in the local time zone.
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.
Date.parse( ), Date.toDateString( ), Date.toLocaleString( ), Date.toTimeString( ), Date.toUTCString( )
Date.toTimeString( ) | return the time portion of a Date as a string |
JavaScript 1.5; JScript 5.5; ECMAScript v3
date.toTimeString( )
A implementation-dependent human-readable string representation of the time portion of date, expressed in the local time zone.
Date.toString( ), Date.toDateString( ), Date.toLocaleDateString( ), Date.toLocaleString( ), Date.toLocaleTimeString( )
Date.toUTCString( ) | convert a Date to a string (universal time) |
JavaScript 1.2; JScript 3.0; ECMAScript v1
date.toUTCString( )
A human-readable string representation, expressed in universal time, of date.
toUTCString( ) returns an implementation-dependent string that represents date in universal time.
Date.UTC( ) | convert a Date specification to milliseconds |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Date.UTC(year, month, day, hours, minutes, seconds, ms)
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.
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));
Date.valueOf( ) | convert a Date to millisecond representation |
Overrides Object.valueOf( )
date.valueOf( )
The millisecond representation of date. The value returned is the same as that returned by Date.getTime( ).
decodeURI( ) | unescape characters in a URI |
JavaScript 1.5; JScript 5.5; ECMAScript v3
decodeURI( uri)
A copy of uri, with any hexadecimal escape sequences replaced with the characters they represent.
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.
decodeURIComponent( ), encodeURI( ), encodeURIComponent( ), escape( ), unescape( )
decodeURIComponent( ) | unescape characters in a URI component |
JavaScript 1.5; JScript 5.5; ECMAScript v3
decodeURI(s)
A copy of s, with any hexadecimal escape sequences replaced with the characters they represent.
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.
decodeURI( ), encodeURI( ), encodeURIComponent( ), escape( ), unescape( )
encodeURI( ) | escape characters in a URI |
JavaScript 1.5; JScript 5.5; ECMAScript v3
encodeURI(uri)
A copy of uri, with certain characters replaced by hexadecimal escape sequences.
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.
// 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
decodeURI( ), decodeURIComponent( ), encodeURIComponent( ), escape( ), unescape( )
encodeURIComponent( ) | escape characters in a URI component |
JavaScript 1.5; JScript 5.5; ECMAScript v3
encodeURIComponent(s)
A copy of s, with certain characters replaced by hexadecimal escape sequences.
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.
encodeURIComponent("hello world?"); // Returns hello%20world%3F
decodeURI( ), decodeURIComponent( ), encodeURI( ), escape( ), unescape( )
Error | a generic exception |
JavaScript 1.5; JScript 5.5; ECMAScript v3
Inherits from Object
new Error( ) new Error(message)
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.
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.
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); } }
EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
Error.message | a human-readable error message |
JavaScript 1.5; JScript 5.5; ECMAScript v3
error.message
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.name | the type of an error |
JavaScript 1.5; JScript 5.5; ECMAScript v3
error.name
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 |
JavaScript 1.5; JScript 5.5; ECMAScript v3
Overrides Object.toString( )
error.toString( )
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1; deprecated in ECMAScript v3
escape(s)
An encoded copy of s in which certain characters have been replaced by hexadecimal escape sequences.
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( ).
escape("Hello World!"); // Returns "Hello%20World%21"
encodeURI( ), encodeURIComponent( ), String, escape( ); Document.cookie in the client-side reference section
eval( ) | execute JavaScript code from a string |
JavaScript 1.0; JScript 1.0; ECMAScript v1
eval(code)
The value of the evaluated code, if any.
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.
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
EvalError | thrown when eval( ) is used improperly |
JavaScript 1.5; JScript 5.5; ECMAScript v3
Inherits from Error
new EvalError( ) new EvalError(message)
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.
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.
Function | a JavaScript function |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Inherits from Object
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
new Function(argument_names..., body) // JavaScript 1.1 and later
A newly created Function object. Invoking the function executes the JavaScript code specified by body.
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.
Function.apply( ) | invoke a function as a method of an object |
JavaScript 1.2; JScript 5.5; ECMAScript v3
function.apply(thisobj, args)
Whatever value is returned by the invocation of function.
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.
// 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);
Function.arguments[] | arguments passed to a function |
JavaScript 1.0; JScript 1.0; ECMAScript v1; deprecated by ECMAScript v3
function.arguments[i] function.arguments.length
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.
Function.call( ) | invoke a function as a method of an object |
JavaScript 1.5; JScript 5.5; ECMAScript v3
function.call(thisobj, args...)
Whatever value is returned by the invocation of function.
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.
// 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);
Function.caller | the function that called this one |
JavaScript 1.0, JScript 2.0; deprecated by ECMAScript
function.caller
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.length | the number of declared arguments |
JavaScript 1.1; JScript 2.0; ECMAScript v1
function.length
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.
Function.prototype | the prototype for a class of objects |
JavaScript 1.1; JScript 2.0; ECMAScript v1
function.prototype
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.
JavaScript 1.1 requires a constructor to be used once before anything can be assigned to its prototype object.
Function.toString( ) | convert a function to a string |
JavaScript 1.0; JScript 2.0; ECMAScript v1
function.toString( )
A string that represents the function.
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.
Global | the global object |
JavaScript 1.0; JScript 1.0; ECMAScript v1
this
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.
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( )."
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.
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.
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";
Infinity | a numeric property that represents infinity |
JavaScript 1.3; JScript 3.0; ECMAScript v1
Infinity
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.)
isFinite( ) | determine whether a number is finite |
JavaScript 1.2; JScript 3.0; ECMAScript v1
isFinite(n)
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.
Infinity, isNaN( ), NaN, Number.NaN, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY
isNaN( ) | check for not-a-number |
JavaScript 1.1; JScript 1.0; ECMAScript v1
isNaN(x)
true if x is (or can be converted to) the special not-a-number value; false if x is any other value.
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.
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
Math | mathematical functions and constants |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.constant Math.function( )
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.
Math.abs( ) | compute an absolute value |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.abs(x)
The absolute value of x.
Math.acos( ) | compute an arc cosine |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.acos(x)
The arc cosine, or inverse cosine, of the specified value x. This return value is between 0 and radians.
Math.asin( ) | compute an arc sine |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.asin(x)
The arc sine of the specified value x. This return value is between -/2 and /2 radians.
Math.atan( ) | compute an arc tangent |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.atan(x)
The arc tangent of the specified value x. This return value is between -/2 and /2 radians.
Math.atan2( ) | compute the angle from the X-axis to a point |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.atan2(y, x)
A value between - and radians that specifies the counterclockwise angle between the positive X-axis and the point (x, y).
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.ceil(x)
The closest integer greater than or equal to x.
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.
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.cos(x)
The cosine of the specified value x. This return value is between -1.0 and 1.0.
Math.E | the mathematical constant e |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.E
Math.E is the mathematical constant e the base of the natural logarithms, with a value of approximately 2.71828.
Math.exp( ) | compute ex |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.exp(x)
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.floor(x)
The closest integer less than or equal to x.
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).
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.LN10 | the mathematical constant loge10 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.LN10
Math.LN10 is loge2, the natural logarithm of 10. This constant has a value of approximately 2.3025850929940459011.
Math.LN2 | the mathematical constant loge2 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.LN2
Math.LN2 is loge2 the natural logarithm of 2. This constant has a value of approximately 0.69314718055994528623.
Math.log( ) | compute a natural logarithm |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.log(x)
The natural logarithm of x.
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.LOG10E | the mathematical constant log10e |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.LOG10E
Math.LOG10E is log10e, the base-10 logarithm of the constant e. It has a value of approximately 0.43429448190325181667.
Math.LOG2E | the mathematical constant log2e |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.LOG2E
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1; enhanced in ECMAScript v3
Math.max(args...)
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1; enhanced in ECMAScript v3
Math.min(args...)
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.PI | the mathematical constant |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.PI
Math.PI is the constant or pi, the ratio of the circumference of a circle to its diameter. It has a value of approximately 3.14159265358979.
Math.pow( ) | compute xy |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.pow(x, y)
x to the power of y, xy.
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 |
JavaScript 1.1; JScript 1.0; ECMAScript v1
Math.random( )
A pseudorandom number between 0.0 and 1.0.
Math.round( ) | round to the nearest integer |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.round(x)
The integer closest to x.
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.sin(x)
The sine of x.
Math.sqrt( ) | compute a square root |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.sqrt(x)
The square root of x. Returns NaN if x is less than zero.
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_2 | the mathematical constant 1/ |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.SQRT1_2
Math.SQRT1_2 is 1/ the reciprocal of the square root of 2. This constant has a value of approximately 0.7071067811865476.
Math.SQRT2 | the mathematical constant |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.SQRT2
Math.SQRT2 is the constant , the square root of 2. This constant has a value of approximately 1.414213562373095.
Math.tan( ) | compute a tangent |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Math.tan(x)
NaN | the not-a-number property |
JavaScript 1.3; JScript 3.0; ECMAScript v1
NaN
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!
Number | support for numbersNumber object |
JavaScript 1.1; JScript 2.0; ECMAScript v1
Inherits from Object
new Number(value) Number(value)
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).
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);
Number.MAX_VALUE | the maximum numeric value |
JavaScript 1.1; JScript 2.0, ECMAScript v1
Number.MAX_VALUE
Number.MAX_VALUE is the largest number representable in JavaScript. Its value is approximately 1.79E+308.
Number.MIN_VALUE | the minimum numeric value |
JavaScript 1.1; JScript 2.0, ECMAScript v1
Number.MIN_VALUE
Number.MIN_VALUE is the smallest (closest to zero, not most negative) number representable in JavaScript. Its value is approximately 5E-324.
Number.NaN | the special not-a-number value |
JavaScript 1.1; JScript 2.0, ECMAScript v1
Number.NaN
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.
Number.NEGATIVE_INFINITY | negative infinity |
JavaScript 1.1; JScript 2.0, ECMAScript v1
Number.NEGATIVE_INFINITY
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.
Number.POSITIVE_INFINITY | infinity |
JavaScript 1.1; JScript 2.0, ECMAScript v1
Number.POSITIVE_INFINITY
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.
Number.toExponential( ) | format a number using exponential notation |
JavaScript 1.5; JScript 5.5, ECMAScript v3
number.toExponential(digits)
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.
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
Number.toFixed( ), Number.toLocaleString( ), Number.toPrecision( ), Number.toString( )
Number.toFixed( ) | format a number using fixed-point notation |
JavaScript 1.5; JScript 5.5, ECMAScript v3
number.toFixed(digits)
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.
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
Number.toExponential( ), Number.toLocaleString( ), Number.toPrecision( ), Number.toString( )
Number.toLocaleString( ) | convert a number to a locally formatted string |
JavaScript 1.5; JScript 5.5, ECMAScript v3
number.toLocaleString( )
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.
Number.toExponential( ), Number.toFixed( ), Number.toPrecision( ), Number.toString( )
Number.toPrecision( ) | format the significant digits of a number |
JavaScript 1.5; JScript 5.5, ECMAScript v3
number.toPrecision(precision)
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.
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
Number.toExponential( ), Number.toFixed( ), Number.toLocaleString( ), Number.toString( )
Number.toString( ) | convert a number to a string |
JavaScript 1.1; JScript 2.0, ECMAScript v1
Overrides Object.toString( )
number.toString(radix)
A string representation of the number.
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.
Number.toExponential( ), Number.toFixed( ), Number.toLocaleString( ), Number.toPrecision( )
Number.valueOf( ) | return the primitive number value |
JavaScript 1.1; JScript 2.0, ECMAScript v1
Overrides Object.valueOf( )
number.valueOf( )
The primitive number value of this Number object. It is rarely necessary to call this method explicitly.
Object | a superclass that contains features of all |
JavaScript objectsJavaScript 1.0; JScript 1.0; ECMAScript v1
new Object( )new Object(value)
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.
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.
Array, Boolean, Function, Function.prototype, Number, String; Chapter 8
Object.constructor | an object's constructor function |
JavaScript 1.1; JScript 2.0; ECMAScript v1
object.constructor
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.
Object.hasOwnProperty( ) | check whether a property is inherited |
JavaScript 1.5; JScript 5.5; ECMAScript v3
object.hasOwnProperty(propname)
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.
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.
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
Function.prototype, Object.propertyIsEnumerable( ); Chapter 8
Object.isPrototypeOf( ) | is one object the prototype of another? |
JavaScript 1.5; JScript 5.5; ECMAScript v3
object.isPrototypeOf(o)
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.
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.
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);
Object.propertyIsEnumerable( ) | will property be seen by a for/in loop? |
JavaScript 1.5; JScript 5.5; ECMAScript v3
object.propertyIsEnumerable(propname)
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.
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.
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
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.
Object.toLocaleString( ) | return an object's localized string representation |
JavaScript 1.5; JScript 5.5; ECMAScript v3
object.toString( )
A string representing the object.
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.
Array.toLocaleString( ), Date.toLocaleString( ), Number.toLocaleString( ), Object.toString( )
Object.toString( ) | define an object's string representation |
JavaScript 1.0; JScript 2.0; ECMAScript v1
object.toString( )
A string representing the object.
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( ));
Object.constructor, Object.toLocaleString( ), Object.valueOf( )
Object.valueOf( ) | the primitive value of the specified object |
JavaScript 1.1; JScript 2.0; ECMAScript v1
object.valueOf( )
The primitive value associated with the object, if any. If there is no value associated with object, returns the object itself.
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.
parseFloat( ) | convert a string to a number |
JavaScript 1.0; JScript 1.0; ECMAScript v1
parseFloat(s)
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.
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( ).
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.
parseInt( ) | convert a string to an integer |
JavaScript 1.0; JScript 1.1; ECMAScript v1
parseInt(s) parseInt(s, radix)
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.
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.
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
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".
RangeError | thrown when a number is out of its legal rangeRangeError object errorsRangeError object |
JavaScript 1.5; JScript 5.5; ECMAScript v3 Inherits from Error
new RangeError( ) new RangeError(message)
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.
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.
ReferenceError | thrown when reading a variable that does not exist ReferenceError object errorsReferenceError object |
JavaScript 1.5; JScript 5.5; ECMAScript v3
Inherits from Error
new ReferenceError( ) new ReferenceError(message)
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.
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.
RegExp | regular expressions for pattern matching RegExp object pattern matching (and regular expressions)RegExp object |
JavaScript 1.2; JScript 3.0; ECMAScript v3
/pattern/attributes
new RegExp(pattern, attributes)
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.
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.
RegExp.exec( ) | general-purpose pattern matching |
JavaScript 1.2; JScript 3.0; ECMAScript v3
regexp.exec(string)
An array containing the results of the match, or null if no match was found. The format of the returned array is described below.
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.
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); }
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.
RegExp.lastIndex, RegExp.test( ), String.match( ), String.replace( ), String.search( ); Chapter 10
RegExp.global | whether a regular expression matches globally global property g attribute (global matching) |
JavaScript 1.2; JScript 5.5; ECMAScript v3
regexp.global
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.ignoreCase | whether a regular expression is case-insensitive ignoreCase property caseinsensitivity toin pattern matching i attribute (case-insensitive matching) |
JavaScript 1.2; JScript 5.5; ECMAScript v3
regexp.ignoreCase
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.lastIndex | the starting position of the next match |
JavaScript 1.2; JScript 5.5; ECMAScript v3
regexp.lastIndex
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.
RegExp.source | the text of the regular expression |
JavaScript 1.2; JScript 3.0; ECMAScript v3
regexp.source
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 |
JavaScript 1.2; JScript 3.0; ECMAScript v3
regexp.test(string)
true if string contains text that matches regexp; false otherwise.
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)
var pattern = /java/i; pattern.test("JavaScript"); // Returns true pattern.test("ECMAScript"); // Returns false
RegExp.exec( ), RegExp.lastIndex, String.match( ), String.replace( ), String.substring( ); Chapter 10
RegExp.toString( ) | convert a regular expression to a string |
JavaScript 1.2; JScript 3.0; ECMAScript v3
Overrides Object.toString( )
regexp.toString( )
A string representation of regexp.
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.
String | support for stringsString object |
JavaScript 1.0; JScript 1.0; ECMAScript v1
Inherits from Object
new String(s) // Constructor function String(s) // Conversion function
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.
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:
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.
String.charAt( ) | get the nth character from a string |
JavaScript 1.0; JScript 1.0, ECMAScript v1
string.charAt(n)
The nth character of string.
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.
String.charCodeAt( ), String.indexOf( ), String.lastIndexOf( )
String.charCodeAt( ) | get the nth character code from a string |
JavaScript 1.2; JScript 5.5; ECMAScript v1
string.charCodeAt(n)
The Unicode encoding of the nth character within string. This return value is a 16-bit integer between 0 and 65535.
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.
JavaScript 1.2 (as implemented by Netscape 4.0, for example) does not have full support for 16-bit Unicode characters and strings.
String.concat( ) | concatenate strings |
JavaScript 1.2; JScript 3.0; ECMAScript v3
string.concat(value, ...)
A new string that results from concatenating each of the arguments to string.
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.
String.fromCharCode( ) | create a string from character encodings |
JavaScript 1.2; JScript 3.0; ECMAScript v1
String.fromCharCode(c1, c2, ...)
A new string containing characters with the specified encodings.
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.
// Create the string "hello" var s = String.fromCharCode(104, 101, 108, 108, 111);
JavaScript 1.2 (as implemented by Netscape 4.0, for example) does not have full support for 16-bit Unicode characters and strings.
String.indexOf( ) | search a stringindexOf() method |
JavaScript 1.0; JScript 1.0, ECMAScript v1
string.indexOf(substring) string.indexOf(substring,start)
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.
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.
In JavaScript 1.0 and 1.1, if start is greater than the length of string, indexOf( ) returns the empty string, rather than -1.
String.charAt( ), String.lastIndexOf( ), String.substring( )
String.lastIndexOf( ) | search a string backwardlastIndexOf() method |
JavaScript 1.0; JScript 1.0, ECMAScript v1
string.lastIndexOf(substring) string.lastIndexOf(substring, start)
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.
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.
String.length | the length of a string |
JavaScript 1.0; JScript 1.0, ECMAScript v1
string.length
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 |
JavaScript 1.5; JScript 5.5; ECMAScript v3
string.localeCompare(target)
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.
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.
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 |
JavaScript 1.2; JScript 3.0; ECMAScript v3
string.match(regexp)
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.
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( ).
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" }
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 |
JavaScript 1.2; JScript 3.0; ECMAScript v3
string.replace(regexp, replacement)
A new string, with the first match, or all matches, of regexp replaced with replacement.
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.
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); });
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 |
JavaScript 1.2; JScript 3.0; ECMAScript v3
string.search(regexp)
The position of the start of the first substring of string that matches regexp, or -1 if no match was found.
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.
var s = "JavaScript is fun"; s.search(/script/i) // Returns 4 s.search(/a(.)a/) // Returns 1
RegExp, RegExp.exec( ), RegExp.test( ), String.match( ), String.replace( ); Chapter 10
String.slice( ) | extract a substring slice() methodString object |
JavaScript 1.2; JScript 3.0; ECMAScript v3
string.slice(start, end)
A new string that contains all the characters of string from and including start and up to but not including end.
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( ).
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
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.
String.split( ) | break a string into an array of stringssplit() methodString object |
JavaScript 1.1; JScript 3.0; ECMAScript v1; enhanced in ECMAScript v3
string.split(delimiter, limit)
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.
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.
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>",""]
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.
String.substr( ) | extract a substring |
JavaScript 1.2; JScript 3.0; deprecated
string.substr(start, length)
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.
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.
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
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.
String.substring( ) | return a substring of a string |
JavaScript 1.0; JScript 1.0, ECMAScript v1
string.substring(from, to)
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.
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.
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.
String.charAt( ), String.indexOf( ), String.lastIndexOf( ), String.slice( ), String.substr( )
String.toLocaleLowerCase( ) | convert a string to lowercase |
JavaScript 1.5; JScript 5.5, ECMAScript v3
string.toLocaleLowerCase( )
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( ).
String.toLocaleUpperCase( ), String.toLowerCase( ), String.toUpperCase( )
String.toLocaleUpperCase( ) | convert a string to uppercase |
JavaScript 1.5; JScript 5.5, ECMAScript v3
string.toLocaleUpperCase( )
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( ).
String.toLocaleLowerCase( ), String.toLowerCase( ), String.toUpperCase( )
String.toLowerCase( ) | convert a string to lowercase |
JavaScript 1.0; JScript 1.0, ECMAScript v1
string.toLowerCase( )
A copy of string, with each uppercase letter converted to its lowercase equivalent, if it has one.
String.toString( ) | return the stringtoString() methodString object |
JavaScript 1.0; JScript 1.0, ECMAScript v1 Overrides Object.toString( )
string.toString( )
The primitive string value of string. It is rarely necessary to call this method.
String.toUpperCase( ) | convert a string to uppercase |
JavaScript 1.0; JScript 1.0, ECMAScript v1
string.toUpperCase( )
A copy of string, with each lowercase letter converted to its uppercase equivalent, if it has one.
String.valueOf( ) | return the string |
JavaScript 1.0; JScript 1.0, ECMAScript v1 Overrides Object.valueOf( )
string.valueOf( )
The primitive string value of string.
SyntaxError | thrown to signal a syntax error SyntaxError object errorsSyntaxError object |
JavaScript 1.5; JScript 5.5; ECMAScript v3
Inherits from Error
new SyntaxError( )new SyntaxError(message)
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.
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.
TypeError | thrown when a value is of the wrong type TypeError object errorsTypeError object data typesTypeError exceptions |
JavaScript 1.5; JScript 5.5; ECMAScript
v3 Inherits from Error
new TypeError( ) new TypeError(message)
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.
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.
undefined | the undefined value |
JavaScript 1.5; JScript 5.5; ECMAScript v3
undefined
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 |
JavaScript 1.0; JScript 1.0; ECMAScript v1; deprecated in ECMAScript v3
unescape(s)
A decoded copy of s.
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.
URIError | thrown by URI encoding and decoding methods URIError object errorsURIError object |
JavaScript 1.5; JScript 5.5; ECMAScript v3 Inherits from Error
new URIError( ) new URIError(message)
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.
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.
Copyright © 2003 O'Reilly & Associates. All rights reserved.