[Contents] [Previous] [Next] [Index]

Chapter 11
Predefined Core Objects and Functions

Several objects are predefined in core JavaScript and can be used in either client-side or server-side scripts. These objects are in addition to objects defined for server-side JavaScript and Navigator objects introduced in Chapter 3, "Using Navigator Objects." A handful of predefined functions can also be used in both client and server scripts.

Objects

The predefined core objects are Array, Boolean, Date, Function, Math, Number, RegExp, and String.

Array Object

JavaScript does not have an explicit array data type. However, you can use the predefined Array object and its methods to work with arrays in your applications. The Array object has methods for manipulating arrays in various ways, such as joining, reversing, sorting them. It has a property for determining the array length and other properties for use with regular expressions.

An array is an ordered set of values that you refer to with 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([element0, element1, ..., elementN])
2. arrayObjectName = new Array([arrayLength])
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.

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

In Navigator 2.0 and Navigator 3.0, arrayLength is the initial length of the array. In Navigator 4.0, if the <SCRIPT> tag does not specify "JavaScript1.2" as the value of the LANGUAGE attribute, this is still true. However, if it does specify "JavaScript1.2", then Array(arrayLength) creates an array of length one with arrayLength as its only element. That is, it no longer considers a single integer argument as a special case.

In Navigator 4.0, in addition to creating arrays using the Array function constructor, you can also create them using literal notation, as described in "Array Literals".

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

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"].

Arrays and Regular Expressions

When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of regexp.exec, string.match, and string.replace. For information on using arrays with regular expressions, see "Regular Expressions".

Boolean Object

Use the predefined 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 "", 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 January 1, 1970, 00:00:00 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 is shown in Figure 11.1.

Figure 11.1    Digital clock example

The <BODY> 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="JavaScript1.2">
<!--
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 predefined JavaScript setTimeout function specifies a time delay to evaluate an expression, in this case a call to JSClock. The second argument indicates 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 predefined 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.

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 the JavaScript Reference.

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 there are differences:

In Navigator 4.0, you can nest a function within a function. (That is, JavaScript now supports lambda expressions and lexical closures.) The nested function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the nested function.

Math Object

The predefined 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.

Table 11.1 summarizes the Math object's methods.

Table 11.1 Methods of Math
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

Unlike many other objects, you never create a Math object of your own. You always use the predefined Math object.

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 cannot change the values of these properties and you use them as follows:

biggestNum = Number.MAX_VALUE
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaN
You always refer to a property of the predefined Number object as shown above, and not as a property of a Number object you create yourself.

Table 11.2 summarizes the Number object's properties.

Table 11.2 Properties of Number
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

RegExp Object

The RegExp object lets you work with regular expressions. It is described in "Regular Expressions".

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 String.substring in the JavaScript Reference.

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")
Table 11.3 summarizes the methods of String objects:

Table 11.3 Methods of String
Method Description
anchor
Creates HTML named anchor

big, blink, bold,
fixed, italics, small,
strike, sub, sup
Creates HTML formatted string

charAt, charCodeAt
Returns the character or character code 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

concat
Combines the text of two strings and returns a new string

fromCharCode
Constructs a string from the specified sequence of ISO-Latin-1 codeset values

split
Splits a String object into an array of strings by separating the string into substrings

slice
Extracts a section of an string and returns a new string.

substring, substr
Returns the specified subset of the string, either by specifying the start and end indexes or the start index and a length

match, replace, search
Used to work with regular expressions

toLowerCase, toUpperCase
Returns the string in all lowercase or all uppercase, respectively

Functions

JavaScript has several "top-level" functions predefined in the language eval, isNan, Number, String, parseInt, parseFloat, escape, unescape, taint, and untaint. For more information on all of these functions, see the JavaScript Reference.

eval Function

The eval function evaluates a string of JavaScript code without reference to a particular object. The syntax of eval is:

eval(expr)
where expr is a string to be evaluated.

If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

isNaN Function

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

isNaN(testValue)
where 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 JavaScript Reference. The syntax of parseFloat is

parseFloat(str)
where 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.

Number and String Functions

The Number and String functions let you convert an object to a number or a string. The syntax of these functions is:

Number(objRef)
String(objRef)
where objRef is an object reference.

The following example converts the Date object to a readable string.

<SCRIPT>
D = new Date (430054663215); 
document.write (String(D) +" <BR>");
</SCRIPT>
This prints "Thu Aug 18 04:37:43 Pacific Daylight Time 1983."

escape and unescape Functions

The escape and unescape functions let you encode and decode strings. The escape function returns the hexadecimal encoding of an argument in the ISO Latin character set. The unescape function returns the ASCII string for the specified value.

The syntax of these functions is:

escape(string)
unescape(string)
These functions are used primarily with server-side JavaScript to encode and decode name/value pairs in URLs.

taint and untaint Functions

The taint and untaint functions are used for adding and removing data tainting in Navigator 3.0. Data tainting prevents other scripts from passing information that should be secure and private, such as directory structures or user session history. JavaScript cannot pass tainted values on to any server without the end user's permission.

For information on tainting, see Chapter 7, "JavaScript Security."


[Contents] [Previous] [Next] [Index]

Last Updated: 10/31/97 14:27:08


Copyright © 1997 Netscape Communications Corporation


Casa de Bender