Built-in objects and functions

n addition to LiveWire objects defined for server-side JavaScript and Navigator objects introduced in Chapter 2, "Using Navigator objects," three additional objects are built in to JavaScript and can be used in either client or server scripts: string, Math, and Date. There are also a handful of built-in functions that can be used in both client and server scripts.

string object

Whenever you assign a string value to a variable or property, you create a string object. For example, the statement

mystring = "Hello, World!"
creates a string object called mystring. String literals are also string objects; for example, the literal "Howdy" is a string object.

A string object has one predefined 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 thirteen to x, because "Hello, World!" has thirteen characters.

A string object has two kinds 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:"")


substring Returns the specified subset of the string
toUpperCase, toLowerCase Returns the string in all uppercase or all lowercase, respectively
indexOf, lastIndexOf Returns the position of specfied substring in the string or last positin of specified substring, respectively
charAt Returns the character at the specified position in string
anchor Creates HTML named anchor
link Creates HTML hyperlink
big, blink, bold, fixed, italics, small, strike, sub, sup Creates HTML formatted string
The following table summarizes the methods of string:

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

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

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

The following table summarizes Math's methods.


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)

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:

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

  • "set" methods, for setting date and time values in Date objects.
  • "get" methods, for getting date and time values from Date objects.
  • "to" methods, for returning string values from Date objects.
  • parse and UTC methods, for parsing Date strings. 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:

  • Seconds and minutes: 0 to 59
  • Hours: 0 to 23
  • Day: 0 to 6 (day of the week)
  • Date: 1 to 31 (day of the month)
  • Months: 0 (January) to 11 (December)
  • Year: years since 1900 For example, suppose you define the following date:

    Xmas95 = new Date("December 25, 1995")
    Then Xmas95.getMonth() returns eleven, and Xmas95.getYear() returns ninety-five.

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

    Built-in functions

    JavaScript has several "top-level" functions built in to the language. They are eval, parseInt, and parseFloat.

    The eval function

    The built-in function eval takes a string as its argument. The string can be any string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

    If the argument represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements.

    This function is useful for evaluating a string representing an arithmetic expression. For example, input from a form element is always a string, but you often want to convert it to a numerical value.

    The following example takes input in a text field, applies the eval function and displays the result in another text field. If you type a numerical expression in the first field and click the button, the expression will be evaluated. For example, enter "(666 * 777) / 3" and click the button to see the result.

    function compute(obj) {
    	obj.result.value = eval(obj.expr.value)
    <FORM NAME="evalform">
    Enter an expression: <INPUT TYPE="text" NAME="expr" SIZE=20 >
    Result: <INPUT TYPE="text" NAME="result" SIZE=20 >
    <INPUT TYPE="button" VALUE="Click Me" onClick="compute(this.form)">
    The display in Navigator looks like this:
    Enter an expression:

    The eval function is not limited to evaluating numerical expressions, however. Its argument can include object references or even JavaScript statements. For example, you could define a function called setValue that would take two arguments, an object and a value, as follows:

    function setValue (myobj, myvalue) {
    	eval ("document.forms[0]." + myobj + ".value") = myvalue
    Then, for example, you could call this function to set the value of a form element "text1" as follows:

    setValue(text1, 42)

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