Built-In JavaScript Objects

In this lesson of the JavaScript tutorial, you will learn...
  1. To work with the built-in String object.
  2. To work with the built-in Math object.
  3. To work with the built-in Date object.

JavaScript has some predefined, built-in objects that do not fit into the HTML DOM, meaning that they are not direct descendants of the window object.

String

In JavaScript, there are two types of string data types: primitive strings and String objects. String objects have many methods for manipulating and parsing strings of text. Because these methods are available to primitive strings as well, in practice, there is no need to differentiate between the two types of strings.

Some common string properties and methods are shown below. In all the examples, the variable MY_STRING contains "Webucator".

Common String Properties
Property Description Example
length
Read-only value containing the number of characters in the string.
MY_STRING.length
//Returns 9
Common String Methods
Method Description Example
charAt(position)
Returns the character at the specified position.
MY_STRING.charAt(4)
//Returns c
charCodeAt(position)
Returns the Unicode character code of the character at the specified position.
MY_STRING.charCodeAt(4)
//Returns 99
fromCharCode(characterCodes)
Returns the text representation of the specifies comma-delimited character codes. Used with String rather than a specific String object.
String.fromCharCode(169)
//Returns ©
indexOf(substring, 
startPosition)
Searches from startPosition for substring. Returns the position at which the substring is found. If substring is not found, returns -1.
MY_STRING.indexOf("cat");
//Returns 4

MY_STRING.indexOf("cat", 5);
//Returns -1
lastIndexOf(substring, 
endPosition)
Searches from the end of the string for substring until endPosition is reached. Returns the position at which the substring is found. If substring is not found, returns -1.
MY_STRING.lastIndexOf("cat");
//Returns 4

MY_STRING.lastIndexOf("cat", 5);
//Returns 4
substring(startPosition, 
endPosition)
Returns the substring beginning at startPosition and ending with the character before endPosition. endPosition is optional. If it is excluded, the substring continues to the end of the string.
MY_STRING.substring(4, 7);
//Returns cat

MY_STRING.substring(4);
//Returns cator
substr(startPosition,
length)
Returns the substring of Length characters beginning at startPosition. length is optional. If it is excluded, the substring continues to the end of the string.
MY_STRING.substr(4, 3);
//Returns cat

MY_STRING.substr(4);
//Returns cator
slice(startPosition, 
endPosition)
Same as substring(startPosition, endPosition).
MY_STRING.slice(4, 7);
//Returns cat
slice(startPosition, 
positionFromEnd)
positionFromEnd is a negative integer. Returns the the substring beginning at startPosition and ending positionFromEnd characters from the end of the string.
MY_STRING.slice(4, -2);
//Returns cat
split(delimiter)
Returns an array by splitting a string on the specified delimiter.
var s = "A,B,C,D";
var a = s.split(",");
document.write(a[2]);
//Returns C
toLowerCase()
Returns the string in all lowercase letters.
MY_STRING.toLowerCase()
//Returns webucator
toUpperCase()
Returns the string in all uppercase letters.
MY_STRING.toUpperCase();
//Returns WEBUCATOR

You can see these examples in a browser by opening BuiltInObjects/Demos/StringPropertiesAndMethods.html.

Math

The Math object is a built-in static object. The Math object's properties and methods are accessed directly (e.g, Math.PI) and are used for performing complex math operations. Some common math properties and methods are shown below.

Common Math Properties
Property Description Example
Math.PI
Pi ()
Math.PI;
//3.141592653589793
Math.SQRT2
Square root of 2.
Math.SQRT2;
//1.4142135623730951
Common Math Methods
Method Description Example
Math.abs(number)
Absolute value of number.
Math.abs(-12);
//Returns 12
Math.ceil(number)
number rounded up.
Math.ceil(5.4);
//Returns 6
Math.floor(number)
number rounded down.
Math.floor(5.6);
//Returns 5
Math.max(numbers)
Highest Number in numbers.
Math.max(2, 5, 9, 3);
//Returns 9
Math.min(numbers)
Lowest Number in numbers.
Math.min(2, 5, 9, 3);
//Returns 2
Math.pow(number, power)
number to the power of power.
Math.pow(2, 5);
//Returns 32
Math.round(number)
Rounded number.
Math.round(2.5);
//Returns 3
Math.random()
Random number between 0 and 1.
Math.random();
//Returns random
//number from 0 to 1

You can see these examples in a browser by opening BuiltInObjects/Demos/MathPropertiesAndMethods.html.

Method for Generating Random Integers

var LOW = 1;
var HIGH = 10;
var RND1 = Math.random();
var RND2 = Math.round(RND1 * (HIGH - LOW) + 1);

Date

The Date object has methods for manipulating dates and times. JavaScript stores dates as the number of milliseconds since January 1, 1970. The sample below shows the different methods of creating date objects, all of which involve passing arguments to the Date() constructor.

Code Sample: BuiltInObjects/Demos/DateObject.html

<html>
<head>
<title>Date Object</title>
</head>
<body>
<h1>Date Object</h1>
<h2>New Date object with current date and time</h2>
<pre>
//Syntax: new Date();
var NOW = new Date();
</pre>
<b>Result:</b>
<script type="text/javascript">
 var NOW = new Date();
 document.write(NOW);
</script>

<h2>New Date object with specific date and time</h2>
<pre>
//Syntax: new Date("month dd, yyyy hh:mm:ss);
var RED_SOX_WINS = new Date("October 21, 2004 12:01:00");
</pre>
<b>Result:</b>
<script type="text/javascript">
 var RED_SOX_WINS = new Date("October 21, 2004 12:01:00");
 document.write(RED_SOX_WINS);
</script>

<pre>
//Syntax: new Date(yyyy, mm, dd, hh, mm, ss, ms);
RED_SOX_WINS = new Date(2004, 9, 21, 12, 01, 00, 00);
</pre>
<b>Result:</b>
<script type="text/javascript">
 RED_SOX_WINS = new Date(2004, 9, 21, 12, 01, 00, 00);
 document.write(RED_SOX_WINS);
</script>
</body>
</html>
Code Explanation

This page is shown in a browser below.

A few things to note:

  • To create a Date object containing the current date and time, the Date() constructor takes no arguments.
  • When passing the date as a string to the Date() constructor, the time portion is optional. If it is not included, it defaults to 00:00:00. Also, other date formats are acceptable (e.g, "10/21/2004" and "10-04-2004").
  • When passing date parts to the Date() constructor, dd, hh, mm, ss, and ms are all optional. The default of each is 0.
  • Months are numbered from 0 (January) to 11 (December). In the example above, 9 represents October.

Some common date methods are shown below. In all the examples, the variable RIGHT_NOW contains "Thu Apr 14 00:23:54:650 EDT 2005".

Common Date Methods
Method Description Example
getDate()
Returns the day of the month (1-31).
RIGHT_NOW.getDate();
//Returns 14
getDay()
Returns the day of the week as a number (0-6, 0=Sunday, 6=Saturday).
RIGHT_NOW.getDay();
//Returns 4
getMonth()
Returns the month as a number (0-11, 0=January, 11=December).
RIGHT_NOW.getMonth();
//Returns 3
getFullYear()
Returns the four-digit year.
RIGHT_NOW.getFullYear();
//Returns 2005
getHours()
Returns the hour (0-23).
RIGHT_NOW.getHours();
//Returns 0
getMinutes()
Returns the minute (0-59).
RIGHT_NOW.getMinutes();
//Returns 23
getSeconds()
Returns the second (0-59).
RIGHT_NOW.getSeconds();
//Returns 54
getMilliseconds()
Returns the millisecond (0-999).
RIGHT_NOW.getMilliseconds();
//Returns 650
getTime()
Returns the number of milliseconds since midnight January 1, 1970.
RIGHT_NOW.getTime();
//Returns 1113452634650
getTimezoneOffset()
Returns the time difference in minutes between the user's computer and GMT.
RIGHT_NOW.getTimezoneOffset();
//Returns 240
toLocaleString()
Returns the Date object as a string.
RIGHT_NOW.toLocaleString();
//Returns Thursday, April 14, 
//2005 12:23:54 AM
toGMTString()
Returns the Date object as a string in GMT timezone.
RIGHT_NOW.toGMTString();
//Returns Thu, 14 Apr 2005 
//04:23:54 UTC 

You can see these examples in a browser by opening BuiltInObjects/Demos/DateMethods.html.

typeof Operator

The typeof operator is used to find out the type of a piece of data. The screenshot below shows what the typeof operator returns for different data types.

Some languages have functions that return the the month as a string. JavaScript doesn't have such a built-in function. The sample below shows a user-defined function that handles this and how the getMonth() method of a Date object can be used to get the month.

Code Sample: BuiltInObjects/Demos/MonthAsString.html

<html>
<head>
<title>Month As String</title>
<script type="text/javascript">
 function monthAsString(num){
  var months = [];
  months[0] = "January";
  months[1] = "February";
  months[2] = "March";
  months[3] = "April";
  months[4] = "May";
  months[5] = "June";
  months[6] = "July";
  months[7] = "August";
  months[8] = "September";
  months[9] = "October";
  months[10] = "November";
  months[11] = "December";

  return months[num-1];
 }

 function enterMonth(){
  var userMonth = prompt("What month were you born?", "");
  alert("You were born in " + monthAsString(userMonth) + ".");
 }
 
 function getCurrentMonth(){
  var today = new Date();
  alert(monthAsString(today.getMonth()));
 }
</script>
</head>
<body>
<form>
 <input type="button" value="CHOOSE MONTH" onclick="enterMonth();">
 <input type="button" value="GET CURRENT MONTH" onclick="getCurrentMonth();">
</form>
</body>
</html>

Built-In JavaScript Objects Conclusion

In this lesson of the JavaScript tutorial, you have learned to work with some of JavaScript's most useful built-in objects.

To continue to learn JavaScript go to the top of this page and click on the next lesson in this JavaScript Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.