Using JavaScript's built-in objects

How to use JavaScript's built-in objects Date, Math, String, Array, and Object

JavaScript sports a number of built-in objects that extend the flexibility of the language. These objects are Date, Math, String, Array, and Object. Several of these objects are "borrowed" from the Java language specification, but JavaScript's implementation of them is different. If you're familiar with Java, you'll want to carefully examine JavaScript's built-in object types to avoid any confusion.

The JavaScript object model is a simple one. The bulk of these objects deal with window content -- documents, links, forms, and so forth. In addition to window-content objects, JavaScript supports a small handful of "built-in" objects. These built-in objects are available regardless of window content and operate independently of whatever page your browser has loaded.

Learning JavaScript

This article is part of the JavaWorld technical content archive. You can learn a lot about JavaScript programming by reading articles in the JavaScript series, just keep in mind that some of the information is likely to be outdated. See "Using JavaScript and forms" and "Debugging JavaScript programs" for more about programming with JavaScript.

The built-in objects are Date, Math, String, Array, and Object. Each is used in a unique and not-quite-consistent way. Furthermore, newer versions of JavaScript (as found in Netscape "Atlas," currently in beta) implement several of these objects in a different manner than in Netscape 2.0. In this column we will address these built-in objects and how to use them. And we'll make note of the quirks you'll encounter as you apply these objects to your JavaScript pages.

Understanding the string object

Of all JavaScript's objects, the String object is the most commonly used. In the Netscape 2.0 JavaScript implementation, new string objects are created implicitly using a variable assignment. For example,

var myString = "This is a string";

creates a string, with the specified text, called myString. In Netscape 2.0, there is no actual object called string, and attempting to instantiate a new String object using the new statement results in an error, as String (or string) is not a defined keyword. In the Atlas version of Netscape, however, String is a bona fide object, and the String keyword can be used to create new strings. The following two approaches are allowed in Atlas, but not in Netscape 2.0.

var myString = new String();
myString = "This is a string";

and

var myString = new String ("This is a string");

String objects have one property: length. The length property returns the length of the string and uses the syntax string.length, where string is the name of the string variable. Both of the following display 16.

alert ("This is a string".length)

and

var myString = "This is a string";
alert (myString.length);

While there may be just one string property, JavaScript supports a large number of methods that can be used with strings. These methods can be roughly divided into two broad camps: string management and text format.

More from JavaWorld

Want more Java enterprise news? Get the JavaWorld Enterprise Java newsletter delivered to your inbox.

String management methods include substring, indexOf, lastIndexOf, and toLowerCase. These are used to return or change the content of the string in some way. For instance, the substring method returns a specified portion of a string. The indexOf method determines the location of a character or group of characters in a string. And the toLowerCase method converts the string to lower case. (As you can imagine, there's also a toUpperCase method.)

Text format methods are used to format text in a document in some special way, and are provided as alternatives to using HTML tags for the same purpose. These methods include big, small, sup, sub, anchor, link, and blink.

String methods can be used directly on strings, or on variables that contain strings. Methods always use open and closed parentheses, even if the method doesn't use parameters. For instance, to convert text to upper case, you'd use one of the following:

var tempVar = "this text is now upper case".toUpperCase();

or

var myString = "this text is now upper case";
var tempVar = myString.toUpperCase();

In Netscape 2.0 there is only one String object, and all strings are created from it. Conversely, strings are first-class objects in Atlas, and each new string is a treated as a separate object. The single-object behavior of strings in Netscape 2.0 can cause some subtle side effects. Take the short script segment that follows. Two strings are created: string1 and string2. A new property (called extra) is assigned to string1. Yet the alert message shows that the property also now belongs to string2.

<SCRIPT>
string1 = "this is string 1"
string2 = "this is string 2"
string1.extra = "new property"
alert (string2.extra)
</SCRIPT>

Technically speaking, strings are "immutable" in JavaScript. That is, the content of the string is static, and cannot be changed. In Netscape 2.0, JavaScript is capable of modifying a string only by creating a new location in memory for it. Because of this, a script that modifies a string many times is prone to memory errors. Each time the string is altered, JavaScript creates a new location in memory for the new version. New strings are created before garbage collection takes place to destroy the old string. Eventually, JavaScript uses all of its available memory, and an "out of memory" error occurs.

A classic example of this problem can be seen in the popular JavaScript "message scrollers," where a message scrolls in the status bar or a text box. For each pass, the scroller redefines the string variable that is displayed. Memory is eventually depleted because JavaScript creates new instances of the string with each pass. For example, the following script will eventually (sooner on some platforms, such as Windows 3.1) cause an "out of memory" error:

<SCRIPT>
var count = 0;
var text = "This is a test of a JavaScript scroller. ";
scroll();
function  scroll () {
        var myString = text.substring (count, text.length) + text.substring (0, count)
        window.status = myString
        if (count < text.length)
                count ++;
        else
                count = 0;
        setTimeout ("scroll()", 333);
        // 333ms is the minimum delay for Netscape 2.0
}
</SCRIPT>

A simple rewrite avoids the problem of creating new blocks of memory. Delete the myString variable assignment, and parse the text directly to the status bar, using window.status.

window.status = text.substring (count, text.length) + text.substring (0, Count)

(While the above approach avoids JavaScript's string-object replication problem, memory leaks still occur because of the use of the setTimeout method. Over many iterations -- typically several thousand or more -- setTimeout will consume all available memory, and eventually JavaScript will display an "out of memory" message.)

For your reference, here are the methods and properties used with JavaScript's string object:

String Properties

lengthThe length of a string

String Methods

anchorCreates a named anchor (hypertext target)
bigSets text to big
blinkSets text to blinking
boldSets text to bold
charAtReturns the character at a specified position
fixedSets text in fixed-pitch font
fontcolorSets the font color
fontsizeSets font size
indexOfReturns the first occurrence of character x starting from position y
italicsSets text to italics
lastIndexOfReturns the last occurrence of character x starting from position y
linkCreates a hyperlink
smallSets text to small
strikeSets text to strikeout
subSets text to subscript
substringReturns a portion of a string
supSets text to superscript
toLowerStringConverts a string to lowercase
toUpperStringConverts a string to uppercase

Using JavaScript as a scientific calculator

JavaScript's Math object provides advanced arithmetic and trigonometric functions, expanding on JavaScript's basic arithmetic operators (plus, minus, multiply, divide). The Math object in JavaScript is borrowed from Java. In fact, the implementation of the Math object in JavaScript closely parallels the Math class in Java, except that the JavaScript Math object offers fewer methods.

JavaScript's Math object properties are treated as constants. In fact, the property names are in all upper-case, following the usual convention of capitalizing variable constants. These properties return often-used values, including pi and the square root of 2. The Math methods are used in mathematical and trigonometric calculations. Handy Math-object methods include ceil, floor, pow, exp (exponent), max, min, round, and random. (Random is only available when using the X Window platform, however.)

The Math object is static, so you don't need to create a new Math object in order to use it. To access the properties and method of the Math object, you merely specify the Math object, along with the method or property you wish. For example, to return the value of pi, you use:

var pi = Math.PI;

Similarly, to use a math method you provide the name of the method, along with the parameters you wish to use. For example, to round the value of pi, you'd use:

var pi = Math.PI;
var pieAreRound = Math.round(pi);       // displays 3

Note that you must specify the Math object by name for each Math method/property you wish to use. JavaScript does not recognize the keywords PI and round all by themselves. Exception: you may use the with statement to associate the names of methods and properties with the Math object. This technique is a handy space-saver when you must use several Math properties and methods. The previous example can be written as

with (Math) {
        var pi = PI;
        var pieAreRound = round(pi);
        alert (pieAreRound)
}

For your reference, here are the properties and methods supported by JavaScript's Math object.

Math Properties

EEuler's constant
LN2The natural logarithm of 2
LN10The natural logarithm of 10
LOG2EThe base 2 logarithm of e
LOG10EThe base 10 logarithm of e
PIThe numeric equivalent of PI: 3.14 etc.
SQRT1_2The square root of one-half
SQRT2The square root of 2

Math Methods

absReturns the absolute value of a number
acosReturns the arc cosine of a number
asinReturns the arc sine of a number
atanReturns the arc tangent of a number
ceilReturns the least integer greater than or equal to a number
cosReturns the cosine of a number
expReturns e (Euler's constant) to the power of a number
floorReturns the greatest integer less than or equal to its argument
logReturns the natural logarithm (base e) of a number
maxReturns the greater of two values
minReturns the lesser of two values
powReturns the value of a number times a specified power
randomReturns a random number (X-platforms only)
roundReturns a number rounded to the nearest whole value
sinReturns the sine of a number
sqrtReturns the square root of a number
tanReturns the tangent of a number

Asking JavaScript for a date

Also borrowed by Java is the Date object, which can be used in JavaScript to determine the current time and date. A popular JavaScript application of the Date object is displaying a digital clock in a text box. The script uses the Date object to update the clock once every second. You also use the Date object to perform date math. For example, your script might determine the number of days between now and a certain future date. You can use this to display a "countdown," such as the number of days left of your company's big sale.

JavaScript treats the Date object like a constructor class. To use Date you must create a new Date object; you can then apply the various Date methods to get and set dates. (The Date object has no properties.) If you're familiar with the Date class in Java, you'll find the properties of the JavaScript Date object largely the same. The most commonly used methods are the get methods, which obtain the time and date of the value in the Date object. These methods are:

  • getHours() - Returns the hour
  • getMinutes() - Returns the minutes
  • getSeconds() - Returns the seconds
  • getYear() - Returns the year ("96" is 1996)
  • getMonth() - Returns the month ("0" is January)
  • getDate() - Returns the day of the month
  • getDay() - Returns the day of the week ("0" is Sunday)

(JavaScript's Date object also provides for setting the time and date of the Date object, but these are seldom used.)

Constructing a new Date object can take several forms. To return an object containing the current date and time, you use the Date object without parameters. In the following, date_obj is a new object, containing the value of the current date and time, as set by the computer's system clock.

var date_obj = new Date();

Alternatively, you can specify a given date and time as part of the date constructor. Either of these methods is allowed -- both set the new date object to January 1, 1997, at midnight local time.

var date_obj = new Date ("January 1 1997 00:00:00")

and

var date_obj = new Date (97, 0, 1, 12, 0, 0)

To use a Date method, append the method to the date object you previously created. For example, to return the current year, use:

var now = new Date();
var yearNow = now.getYear();

For your reference, here are the methods supported by JavaScript's Date object.

1 2 Page 1
Page 1 of 2