News Outline Schedule Tutorials Project Tools Links

Built In JavaScript Objects

JavaScript has several pre-made Objects defined with properties and methods to make the life of programmers much easier. Some of those Objects include the Math, String, and Date objects. On an Object, a property has no brackets or parameters - it is just a variable or constant, which is attached to the Object. A method is a function that is attached to the Object, usually one which operates on the data being stored by the Object. The way in which they are attached to the Object is through the use of the . character, for example the length property of the Array Object potato would be called potato.length. (This is also the reason why .s are not allowed in variable names in Javascript.)

In many cases, in order to use a method or property, you will create what is called an instance of the object with the new command, just like with the Array Object in the last tutorial. You would then refer to the properties and methods as part of that new Object. For example, to get the length of a string, you would create a string, we'll call it bob, and then refer to bob.length to get its length, or bob.big() to return it's contents formated with the HTML tag <BIG>, like in the following example:

// First, we create our new string in a variable: var bob = "this is a string"; // Next, we can check how long the string is with bob.length window.alert("String bob is " + bob.length + " characters long!"); // Then we could print out our string inside bold tags like this: document.write( bob.bold() );

Some of Javascript's pre-made objects however, do not require that you create a new copy in order to use them. One example of this would be the Math object - it comes with built-in functions and properties to assist with all sorts of mathematical calculations which would be very difficult otherwise, such as creating random numbers, or finding the square root of a number. Here are an example of both a property, and a method being called from the Math Object:

// Here is a property, which stores the value of Pi: var a = Math.PI; // And here is the sqrt() method, which returns the square root of // the parameter it is passed: var b = Math.sqrt(9);

1: Math

The Math object has several useful properties and methods defined on it, all of which are related to mathematics. In the case of this particular object, you would always access these functions directly from it, since there is no actual need to create an instance of this object - it's designed to hold a group of related functions and nothing more. Here is an index of some of the more usefull properties and methods on the Math object:

Property or
"Method"
Explanation &
Example of use
Math.PI Approximately 3.141592653589793, depending on browser.
var diameter = 2 * Math.PI * radius;
Math.random() Generates random decimal numbers between 0 and 1
var randNum = Math.random * 10; // Now between 0 and 10
Math.round( X ) Rounds numbers off to the nearest integer value.
var thisNum = Math.round( 2.7 ); // puts 3 in thisNum
Math.floor( X ) Rounds numbers down to the nearest integer which is not more than X
var thisNum = Math.floor( 2.7 ); // puts 2 in thisNum
Math.ceil( X ) Rounds numbers up to the nearest integer which is not less than X
var thisNum = Math.floor( 1.2 ); // puts 2 in thisNum
Math.abs( X ) Gives the absolute value of X
var thisNum = Math.abs( -2.7 ); // puts 2.7 in thisNum
Math.sqrt( X ) Gives the square root of X
var thisNum = Math.sqrt( 9 ); // puts 3 in thisNum
Math.cos( X ) Gives the trigonometric cosine of X. (X should be in radians)
var thisNum = Math.cos( 0 ); // puts 1 in thisNum
Math.sin( X ) Gives the trigonometric sine of X. (X should be in radians)
var thisNum = Math.sin( 0 ); // puts 0 in thisNum
Math.tan( X ) Gives the trigonometric tangent of X. (X should be in radians)
var thisNum = Math.tan( 0 ); // puts 0 in thisNum
Math.pow( X , Y ) Returns X raised to the power of Y
var thisNum = Math.pow( 2 , 3 ); // puts 8 in thisNum
Math.max( X , Y ) Returns the larger of either X or Y
var thisNum = Math.max( 2 , 8 ); // puts 8 in thisNum
Math.min( X , Y ) Returns the smaller of either X or Y
var thisNum = Math.max( 2 , 8 ); // puts 2 in thisNum

2: String

The String Object is one that we've been using all along, without realizing it. It has only one real property, which is length - similar to the length property of the Array, the String's length will tell you how many characters are contained in the string. The methods of the String Object can be used to manipulate the string, and it's contents, as shown in the following examples:

// first, we need two strings to use these methods on: var thisStr = "abcdefghijklmnop"; var thatStr = "The Rain In Windsor Is Wet"; // Now let's print out the length of each string: document.writeln( thisStr.length + "<br />" ); document.writeln( thatStr.length + "<br />" ); // Now let's experiment with a few formatting functions, to // change things to upper or lower case. (remember, you can // also store these results in a variable or use them for // comparisons in if statements) document.writeln( thatStr.toLowerCase() + "<br />" ); document.writeln( thatStr.toUpperCase() + "<br />" ); // Methods also exist which wrap the contents of the string // in a variety of HTML tags, including bold(), italics(), fixed(), // small(), big(), strike(), sub(), and sup(), but they save // very little effort, so they're not demonstrated here. // Next are some methods for searching through the contents // of a string to see if something you're looking for is there: // indexOf() tells you where the sub-string you're looking for // starts inside of your main string, starting from the start // if the string. // lastIndexOf() does the same thing, but starts searching from // the end of the string instead of the beginning. Thus: document.writeln( thatStr.indexOf("I") + "<br />" ); document.writeln( thatStr.lastIndexOf("I") + "<br />" ); // give different results, as they each find a different "I" in // thatStr. If either is used to search for something which is // not actually in the main string, they will return a value // of -1. (Remember, 0 is the index of the first character in // the string.) if( thatStr.indexOf( "hello" ) == -1 ) { document.writeln("Not found... <br />" ); } else { document.writeln("Found...<br />" ); }; // Next, we can chop out smaller parts of strings for our own use. // The methods substr() and substring() seem very similar, but there is // an important difference: in substr(), you give the index you wish // your new string to start at, and the length you wish to take, but // in substring() you give two indexes - and your string is whatever // comes between them. (always make sure your second index in substring() // is higher than the first one, otherwise weird things can happen.) document.writeln( thisStr.substr(2,4) + "<br />" ); document.writeln( thisStr.substring(2,4) + "<br />" ); // in the first case, we get a 4 character string "cdef" from substr, but // substring() with the same parameters gives us only 2 characters, from indexes // 2 and 3! (The second parameter is the index after the end of our sub-string.) // Next, we may want to switch something around in a string - for example, // if you wanted to change the statement in thatStr to say Water instead // or Rain, this is what you could do: document.writeln( thatStr.replace( "Rain" , "Water" ) + "<br />" ); // The replace() method on the string object takes two parameters - the old // string, which is to be removed, and the new string, which will be put into // it's place. // Lastly, if you wish to know what character is at a specific location // in a string, you can use a method called charAt() to tell you. document.writeln( thisStr.charAt( 1 ) + "<br />" ); // This will give us the character at index 1 in thisStr, or b. // (always remember that the indexes in strings and arrays always start // at zero!)

3: Date

The Date Object is a very useful one - it can be used to display the 'current date' on the user's computer, (assuming that their clock is set correctly, that is,) or it can (through the use of some math) be used as part of a script to display a count down until an important event. (You may have seen the occasional web site before the release of the next Star Wars movie, which was counting down the number of Days, Hours, Minutes, and Seconds until the movie opened. This was done with the Date Object.) When you first initialize the Date Object, you can either do so with no parameters, in which case, the value stored will be the current date & time on the user's machine, or you can set a specific date and time, like this:

// The current date: var timeNow = new Date(); // A long time ago: var timeThen = new Date(1974, 2, 17, 18, 05, 0, 0); // A long time to come: var timeWhen = new Date("Mon Oct 08 10:23:21 GMT-0400 (EDT) 2001");

Note that when performing addition and subtraction on the Date Object, it is converted into an integer number, representing the number of milliseconds between the time it stores, and January 1st, 1970. Thus, to get the time difference between timeNow and timeWhen, you would first subtract timeNow from timeWhen, and then divide the result by 1000 to get the number of seconds, by 60000 to get the number of minutes, and on until you had the units you were looking for.

Here are some of the more usefull methods on the Date Object, and examples of how they would be used, assuming we created the date objects from the previous code block:

"Method" Explanation
timeThen.getFullYear() Returns the four digit year as stored in the date object in timeThen
timeThen.getMonth() Returns the month as stored in the date object in timeThen as a number between 0 (January) and 11 (December)
timeThen.getDate() Returns the day of the month as stored in the date object in timeThen as a number between 1 and 31
timeThen.getDay() Returns the day of the week as stored in the date object in timeThen as a number from 0 (Sunday) to 6 (Saturday)
timeThen.getHours() Returns the hours part of the time stored in the date object in timeThen - the numbers returned are from 0 to 23 (24 hour clocks)
timeThen.getMinutes() Returns the minutes part of the time stored in the date object in timeThen
timeThen.getSeconds() Returns the seconds part of the time stored in the date object in timeThen
timeThen.getMilliseconds() Returns the milliseconds part of the time stored in the date object in timeThen
timeThen.getTime() Returns the number of milliseconds between the date object in timeThen and January 1st, 1970, GMT. Warning! This number will be very large!
timeThen.setFullYear( 1972 ) Sets the four digit year stored in the date object in timeThen to 1972
timeThen.setMonth( 2 ) Sets the month stored in the date object in timeThen to 2 (March) - numbers used should go from 0 to 11.
timeThen.setDate( 4 ) Sets the day of the month stored in the date object in timeThen to 4 - the day input should be from 1 to 31 (or however many days are in that particular month.)
timeThen.setHours( 5 ) Sets the hour part of the time stored in the date object in timeThen to 5 (the hours are stored in 24 hour time, so 5pm would be 17)
timeThen.setMinutes( 23 ) Sets the minutes part of the time stored in the date object in timeThen to 23
timeThen.setSeconds( 19 ) Sets the seconds part of the time stored in the date object in timeThen to 19
timeThen.setMilliseconds( 7 ) Sets the milliseconds part of the time stored in the date object in timeThen to 7
timeThen.setTime(99999999) Sets the number of milliseconds between the date object in timeThen and January 1st, 1970. Warning! This number will need to be very large - the example here (99999999) only sets the date to Thu Jan 01 1970 22:46:39 EST! The best way to use this method is to first get the current time in milliseconds from the getTime() method, then add or subtract a number of milliseconds and put the number back into the date object with setTime().
timeThen.toString() Returns the date/time stored in timeThen as a formated, readable string, like this:
Sat Mar 04 1972 05:23:19 GMT-0500 (EST)

4: Miscellaneous Built In Functions

In addition to the previously mentioned built in objects, there are a number of useful Javascript functions which are not actually attached to any specific object. Here are a few of them:

parseInt(X)Converts the string X into an integer number represented at the start of the string. Stops as soon as any character that is not part of an integer number is found - if no number is located at the start of the string, returns the special error code NaN.
parseFloat(X)Converts the string X into a "Floating Point" number (ie: with decimal places) represented at the start of the string. Stops as soon as any character that is not part of a floating point number is found - if no number is located at the start of the string, returns the special error code NaN.
isNaN(X)Returns true if the variable X contains the NaN error code, or false otherwise. Intended for use in conditional statements, to determine if provided input was really a number after it is processed by parseInt() or parseFloat()