Built-in objects and functions

everal objects are built in to JavaScript and can be used in either client or server scripts. These objects are in addition to LiveWire objects defined for server-side JavaScript and Navigator objects introduced in Chapter 2, "Using Navigator objects." A handful of built-in functions can also be used in both client and server scripts.


Built-in objects

The built-in objects are Array, Boolean, Date, Function, Math, Number, and String.

Array object

JavaScript does not have an explicit array data type. However, you can use the built-in Array object and its methods to work with arrays in your applications. The Array object has methods for joining, reversing, and sorting arrays. It has a property for determining the array length.

An array is an ordered set of values that you reference through a name and an index. For example, you could have an array called emp that contains employees' names indexed by their employee number. So emp[1] would be employee number one, emp[2] employee number two, and so on.

To create an Array object:

1. arrayObjectName = new Array([arrayLength])
2. arrayObjectName = new Array([element0, element1, ..., elementn])

arrayObjectName is either the name of a new object or a property of an existing object. When using Array properties and methods, arrayObjectName is either the name of an existing Array object or a property of an existing object.

arrayLength is the initial length of the array. You can access this value using the length property.

elementn is a list of values for the array's elements. When this form is specified, the array is initalized with the specified values as its elements, and the array's length property is set to the number of arguments.

The Array object has the following methods:

For example, suppose you define the following array:

myArray = new Array("Wind","Rain","Fire")

myArray.join() returns "Wind,Rain,Fire"; myArray.reverse transposes the array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind". myArray.sort sorts the array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind". myArray.

Populating an array

You can populate an array by assigning values to its elements. For example,

emp[1] = "Casey Jones"
emp[2] = "Phil Lesh"
emp[3] = "August West"

You can also populate an array when you create it:

myArray = new Array("Hello", myVar, 3.14159)

The following code creates a two-dimensional array and displays the results.

a = new Array(4)
for (i=0; i < 4; i++) {
   a[i] = new Array(4)
   for (j=0; j < 4; j++) {
      a[i][j] = "["+i+","+j+"]"
   }
}
for (i=0; i < 4; i++) {
   str = "Row "+i+":"
   for (j=0; j < 4; j++) {
      str += a[i][j]
   }
   document.write(str,"<p>")
}

This example displays the following results:

Multidimensional array test

Row 0:[0,0][0,1][0,2][0,3]

Row 1:[1,0][1,1][1,2][1,3]

Row 2:[2,0][2,1][2,2][2,3]

Row 3:[3,0][3,1][3,2][3,3]

Referring to array elements

You can refer to an array's elements by using the element's value or ordinal number. For example, suppose you define the following array:

myArray = new Array("Wind","Rain","Fire")

You can then refer to the first element of the array as myArray[0] or myArray["Wind"].

Boolean object

Use the built-in Boolean object when you need to convert a non-boolean value to a boolean value. You can use the Boolean object any place JavaScript expects a primitive boolean value. JavaScript returns the primitive value of the Boolean object by automatically invoking the valueOf method.

To create a Boolean object:

booleanObjectName = new Boolean(value)

booleanObjectName is either the name of a new object or a property of an existing object. When using Boolean properties, booleanObjectName is either the name of an existing Boolean object or a property of an existing object.

value is the initial value of the Boolean object. The value is converted to a boolean value, if necessary. If value is omitted or is 0, null, false, or the empty string "", it the object has an initial value of false. All other values, including the string "false" create an object with an initial value of true.

The following examples create Boolean objects:

bfalse = new Boolean(false)
btrue = new Boolean(true)

Date object

JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.

JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00.

Note

Currently, you cannot work with dates prior to January 1, 1970.

To create a Date object:

dateObjectName = new Date([parameters])

where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.

The parameters in the preceding syntax can be any of the following:

Methods of the Date object

The Date object methods for handling dates and times fall into these broad categories:

With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:

For example, suppose you define the following date:

Xmas95 = new Date("December 25, 1995")

Then Xmas95.getMonth() returns 11, and Xmas95.getYear() returns 95.

The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since the epoch for a Date object.

For example, the following code displays the number of days left in the current year:

today = new Date()
endYear = new Date("December 31, 1990") // Set day and month
endYear.setYear(today.getYear()) // Set year to this year
msPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per day
daysLeft = (endYear.getTime() - today.getTime()) / msPerDay
daysLeft = Math.round(daysLeft)
document.write("Number of days left in the year: " + daysLeft)

This example creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days.

The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object:

IPOdate = new Date()
IPOdate.setTime(Date.parse("Aug 9, 1995"))

Using the Date object: an example

The following example shows a simple application of Date: it displays a continuously-updated digital clock in an HTML text field. This is possible because you can dynamically change the contents of a text field with JavaScript (in contrast to ordinary text, which you cannot update without reloading the document).

The display in Navigator looks like this:

     JavaScript clock

     The current time is

The &LT;BODY&GT: of the document is:

<BODY ONLOAD="JSClock()">
<FORM NAME="clockForm">
The current time is <INPUT TYPE="text" NAME="digits" SIZE=12 VALUE="">
</FORM>
</BODY>

The <BODY> tag includes an onLoad event handler. When the page loads, the event handler calls the function JSClock, defined in the <HEAD>. A form called clockForm includes a single text field named digits, whose value is initially an empty string.

The <HEAD> of the document defines JSClock as follows:

<HEAD>
<SCRIPT language="JavaScript">
<!--
function JSClock() {
          var time = new Date()
          var hour = time.getHours()
          var minute = time.getMinutes()
          var second = time.getSeconds()
          var temp = "" + ((hour > 12) ? hour - 12 : hour)
          temp += ((minute < 10) ? ":0" : ":") + minute
          temp += ((second < 10) ? ":0" : ":") + second
          temp += (hour >= 12) ? " P.M." : " A.M."
          document.clockForm.digits.value = temp
          id = setTimeout("JSClock()",1000)
}
//-->
</SCRIPT>
</HEAD>

The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute and seconds to hour, minute, and second.

The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour - 13), otherwise simply hour.

The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way.

Finally, a conditional expression appends "PM" to temp if hour is 12 or greater; otherwise, it appends "AM" to temp.

The next statement assigns the value of temp to the text field:

document.aform.digits.value = temp

This displays the time string in the document.

The final statement in the function is a recursive call to JSClock:

id = setTimeout("JSClock()", 1000)

The built-in JavaScript setTimeout function specifies a time delay to evaluate an expression, in this case a call to JSClock. The second argument indicates a a delay of 1,000 milliseconds (one second). This updates the display of time in the form at one-second intervals.

Note that the function returns a value (assigned to id), used only as an identifier (which can be used by the clearTimeout method to cancel the evaluation).

Function object

The built-in Function object specifies a string of JavaScript code to be compiled as a function.

To create a Function object:

functionObjectName = new Function ([arg1, arg2, ... argn], functionBody)

functionObjectName is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror. When using Function properties, functionObjectName is either the name of an existing Function object or a property of an existing object.

arg1, arg2, ... argn are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm".

functionBody is a string specifying the JavaScript code to be compiled as the function body.

Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.

In addition to defining functions as described here, you can also use the function statement, as described in "function".

The following code assigns a function to the variable setBGColor. This function sets the current document's background color.

var setBGColor = new Function("document.bgColor='antiquewhite'")

To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable:

var colorChoice="antiquewhite"
if (colorChoice=="antiquewhite") {setBGColor()}

You can assign the function to an event handler in either of the following ways:

1. document.form1.colorButton.onclick=setBGColor
2. <INPUT NAME="colorButton" TYPE="button"
      VALUE="Change background color"
      onClick="setBGColor()">

Creating the variable setBGColor shown above is similar to declaring the following function:

function setBGColor() {
   document.bgColor='antiquewhite'
}

Assigning a function to a variable is similar to declaring a function, but they have differences:

Math object

The built-in Math object has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi (3.141...), which you would use in an application as

Math.PI

Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write

Math.sin(1.56)

Note that all trigonometric methods of Math take arguments in radians.

The following table summarizes Math's methods.

Method Description
abs
Absolute value
sin, cos, tan
Standard trigonometric functions; argument in radians
acos, asin, atan
Inverse trigonometric functions; return values in radians
exp, log
Exponential and natural logarithm, base e
ceil
Returns least integer greater than or equal to argument
floor
Returns greatest integer less than or equal to argument
min, max
Returns greater or lesser (respectively) of two arguments
pow
Exponential; first argument is base, second is exponent
round
Rounds argument to nearest integer
sqrt
Square root

It is often convenient to use the with statement when a section of code uses several math constants and methods, so you don't have to type "Math" repeatedly. For example,

with (Math) {
          a = PI * r*r
          y = r*sin(theta)
          x = r*cos(theta)
}

Number object

The Number object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You use these properties as follows:

biggestNum = Number.MAX_VALUE
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaN

The following table summarizes Number's properties.

Method Description
MAX_VALUE
The largest representable number
MIN_VALUE
The smallest representable number
NaN
Special "not a number" value
NEGATIVE_INFINITY
Special infinite value; returned on overflow
POSITIVE_INFINITY
Special negative infinite value; returned on overflow

String object

JavaScript does not have a string data type. However, you can use the String object and its methods to work with strings in your applications. The String object has a large number of methods for manipulating strings. It has one property for determining the string's length.

To create a String object:

stringObjectName = new String(string)

stringObjectName is the name of a new String object.

string is any string.

For example, the following statement creates a String object called mystring:

mystring = new String ("Hello, World!")

String literals are also String objects; for example, the literal "Howdy" is a String object.

A String object has one property, length, that indicates the number of characters in the string. So, using the previous example, the expression

x = mystring.length

assigns a value of 13 to x, because "Hello, World!" has 13 characters.

A String object has two types of methods: those that return a variation on the string itself, such as substring and toUpperCase, and those that return an HTML-formatted version of the string, such as bold and link.

For example, using the previous example, both mystring.toUpperCase() and "hello, world!".toUpperCase() return the string "HELLO, WORLD!".

The substring method takes two arguments and returns a subset of the string between the two arguments. Using the previous example, mystring.substring(4, 9) returns the string "o, Wo." For more information, see the reference topic for substring.

The String object also has a number of methods for automatic HTML formatting, such as bold to create boldface text and link to create a hyperlink. For example, you could create a hyperlink to a hypothetical URL with the link method as follows:

mystring.link("http://www.helloworld.com")

The following table summarizes the methods of String objects:

Method Description
anchor
Creates HTML named anchor
big, blink, bold, fixed, italics, small, strike, sub, sup
Creates HTML formatted string
charAt
Returns the character at the specified position in string
indexOf, lastIndexOf
Returns the position of specified substring in the string or last position of specified substring, respectively
link
Creates HTML hyperlink
split
Splits a String object into an array of strings by separating the string into substrings
substring
Returns the specified subset of the string
toLowerCase, toUpperCase
Returns the string in all lowercase or all uppercase, respectively


Built-in functions

JavaScript has two "top-level" functions built in to the language: parseInt and parseFloat.

isNaN function

The isNaN function evaluates an argument to determine if it is "NaN" (not a number).

The syntax of isNaN is:

isNaN(testValue)

testValue is the value you want to evaluate.

On platforms that support NaN, the parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. isNaN returns true if passed "NaN," and false otherwise.

The following code evaluates floatValue to determine if it is a number and then calls a procedure accordingly:

floatValue=parseFloat(toFloat)

if (isNaN(floatValue)) {
   notFloat()
} else {
   isFloat()
}

parseInt and parseFloat functions

The two "parse" functions, parseInt and parseFloat, return a numeric value when given a string as an argument. For detailed descriptions and examples, see the reference topics.

The syntax of parseFloat is

parseFloat(str)

parseFloat parses its argument, the string str, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number).

The syntax of parseInt is

parseInt(str [, radix])

parseInt parses its first argument, the string str, and attempts to return an integer of the specified radix (base), indicated by the second, optional argument, radix. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The parseInt function truncates numbers to integer values.