Understanding built-in objects in JavaScript

Gain a foundational understanding of the intrinsic objects available in the JavaScript language.

Kris Hadlock (kris@krishadlock.com), Web Developer/Designer, Studio Sedition

Photo of Kris HadlockKris Hadlock has been a contract web developer and designer since 1996. He has worked on projects for companies such as SPIN Magazine, IKEA, United Airlines, JP Morgan Chase, GoDaddy Software, and Fire Mountain Gems. He is the author of Ajax for Web Application Developers (Sams) and The ActionScript Migration Guide (New Riders) as well as a featured columnist and writer for numerous websites and design magazines, including Peachpit.com, InformIT.com, and Practical Web Design magazine. Kris is also the founder of www.studiosedition.com, a web design and software development studio specializing in fusion of form and function.



16 August 2011

Also available in Chinese Russian Japanese

All programming languages have intrinsic (or built-in) objects that create the essential functionality of the language. Intrinsic objects are the foundation of the language in which you write custom code that powers custom functionality based on your imagination. JavaScript has many intrinsic objects that define it as a language. This article covers some of the most commonly used objects and provides a basic understanding of what the functions are and how to use them.

Develop skills on this topic

This content is part of a progressive knowledge path for advancing your skills. See A comprehensive guide to JavaScript.

Number

The JavaScript Number object is a wrapper for numeric values. You can use it in combination with the new keyword and set it to a variable to be used later in JavaScript code:

var myNumber = new Number(numeric value);

Alternatively, you can create a Number object simply by setting a variable to a numeric value. This variable will then have access to the properties and methods available to the object.

In addition to storing numeric values, the Number object includes various properties and methods for manipulating or retrieving information about numbers. All of the properties available to the Number object are read-only constants, meaning that their values always remain the same and cannot be changed. Four properties are included in the Number object:

  • MAX_VALUE
  • MIN_VALUE
  • NEGATIVE_INFINITY
  • POSITIVE_INFINITY

The MAX_VALUE property returns the value 1.7976931348623157e+308, which is the largest number JavaScript can handle:

document.write(Number.MAX_VALUE);
// Result is: 1.7976931348623157e+308

Alternatively, using MIN_VALUE returns the value 5e-324, which is the smallest number possible in JavaScript:

document.write(Number.MIN_VALUE);
// Result is: 5e-324

NEGATIVE_INFINITY is the largest negative number JavaScript can handle, represented as -Infinity:

document.write(Number.NEGATIVE_INFINITY);
// Result is: -Infinity

The POSITIVE_INFINITY property is anything larger than MAX_VALUE and is represented as Infinity:

document.write(Number.POSITIVE_INFINITY);
// Result is: Infinity

The Number object also has methods that you can use to format or convert numeric values. The methods are:

  • toExponential
  • toFixed
  • toPrecision
  • toString
  • valueOf

Each method essentially does exactly as it is named—for example, the toExponential method returns a string representation of a number in exponential form. The uniqueness of each method is in the arguments it excepts. The toExponential method has an optional argument that can be used to set how many significant digits to use, the toFixed method determines the post-decimal precision based on the argument passed, and the toPrecision method determines the significant digits to display based on the argument passed.

Each object in JavaScript includes a toString and valueOf method, so those methods aren't covered in the proceeding sections. The toString method returns a string representation of a number (in this case), but in other objects, it returns a string representation of that object type. The valueOf method returns the primitive value of the object type that calls it—in this case, the Number object.

The Number object alone might not seem terribly powerful, but it is an essential part of any programming language, and JavaScript is no exception. The JavaScript Number object provides the foundation for any mathematical procedures, which is essentially the foundation of all programming languages.


Boolean

The Boolean object is necessary when attempting to create any sort of logic in JavaScript. A Boolean is an object that represents a true or a false value. The Boolean object has a number of values that qualify as a value equal to false (0 , -0, null, or "" [an empty string]), undefined (NaN), and of course, false. All other Boolean values qualify as a value equal to true. The object can be instantiated using the new keyword but is most often a variable set to a true or false value:

var myBoolean = true;

The Boolean object includes the toString and valueOf methods, although it's unlikely that you will need to use them. The Boolean object is most commonly used for simple evaluation of a true or false value in conditional statements. The combination of Booleans and conditional statements provides a way to create logic using JavaScript. Examples of such conditional statements are the if, if...else, if...else...if, and switch statements. When combined with a conditional statement, you can use Booleans to determine a result based on the conditions that you script. Listing 1 shows a simple example of a conditional statement combined with a Boolean.

Listing 1. A conditional statement combined with a Boolean
var myBoolean = true;
if(myBoolean == true) {
   // If the condition evaluates to true
}
else {
   // If the condition evaluates to false
}

It goes without saying that the Boolean object is an extremely important part of JavaScript. Without a Boolean object, there wouldn't be anything to evaluate within conditional statements.


String

The JavaScript String object is a wrapper for text values. In addition to storing text, the String object includes a property and various methods to manipulate or gather information about text. Like the Boolean object, the String object doesn't need to be instantiated to be used—for example, you can set a variable to a string, and then all of the String object properties or methods will become available to that variable:

var myString = "My string";

The String object only has one property—length—which is read only. You use the length property to return the length of a string only: You cannot change it externally. The code that follows provides an example using the length property to determine the number of characters in a string:

var myString = "My string";
document.write(myString.length);
// Results in a numeric value of 9

The result of this code is 9, because the space between the two words is also counted as a character.

There are quite a few methods in the String object that you can use to manipulate and gather information about text. The following is a list of the available methods:

  • charAt
  • charCodeAt
  • concat
  • fromCharCode
  • indexOf
  • lastIndexOf
  • match
  • replace
  • search
  • slice
  • split
  • substr
  • substring
  • toLowerCase
  • toUpperCase

The chartAt method can be used to retrieve a specific character based on an index that you pass as an argument. The code that follows provides an example of how to return the first character of a string:

var myString = "My string";
document.write(myString.chartAt(0);
// Results in M

If you need the opposite result, there are a couple of methods that return the index of a specified character or set of characters in a string rather than returning a character using an index. These methods are indexOf and lastIndexOf, both of which include two parameters: searchString and start. The searchString parameter is the starting index, and the start parameter tells the method where to begin the search. The difference between these two methods is that indexOf returns the first occurrence, and lastIndexOf returns the last occurrence.

The charCodeAt method is similar to charAt: The only difference is that it returns the Unicode character. Another Unicode-related method that the String object includes is fromCharCode, which converts Unicode to characters.

If you're looking to combine strings, you can either add them together using the plus sign (+) or you can more appropriately use the concat method. This method accepts an unlimited number of string arguments, joins them, and returns the combined result as a new string. Listing 2 shows an example of how to combine multiple strings as one using concat instance.

Listing 2. Combining multiple strings using the concat method
var myString1 = "My";
var myString2 = " ";
var myString3 = "string";
document.write(myString.concat(myString1, myString2, myString3);
// Results in "My String"

There is also a group of String methods that accept a regular expression as an argument to find or modify a string. These include the match, replace, and search methods. The match method uses the regular expression to search a specific string and returns all matches. The replace method actually accepts a substring or a regular expression and a replacement string as its second parameter, replaces all matches with the replacement string, and returns the updated string. The last of these methods is the search method, which searches for a match of a regular expression and returns its position.

When it's necessary to alter a string, a number of methods come in handy. The first is the slice method, which extracts and returns part of a string based on an index or the combination of a beginning and ending index. Another such method is the split method. The split method splits a string into an array of substrings wherever the separator argument is found. For example, if a comma (,) is passed as an argument, the string will be split at every comma into a new substring. The next methods that can alter a string are the substr method, which extracts characters from a string based on the start position and length specified as arguments, and the substring method, which extracts characters from a string based on the two indices specified as arguments. The final methods that can alter a string are toLowerCase and toUpperCase, which convert the characters in a string to lowercase and uppercase letters, respectively. These methods are useful when comparing string values, as strings can sometimes have inconsistencies in case. These methods ensure that you're comparing the value, not the case.


Date

The JavaScript Date object provides a way to work with dates and times. You can instantiate it in a number of different ways depending on the desired results. For example, you can instantiate it with no arguments:

var myDate = new Date();

Or pass milliseconds as an argument:

var myDate = new Date(milliseconds);

You can pass a date string as an argument:

var myDate = new Date(dateString);

Or you can pass multiple arguments to create a complete date:

var myDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);

In addition, several methods are available to the Date object that you can use once the object has been instantiated. Most of the available methods revolve around getting a specific portion of the current time. The following methods are the getter methods available to the Date object:

  • getDate
  • getDay
  • getFullYear
  • getHours
  • getMilliseconds
  • getMinutes
  • getMonth
  • getSeconds
  • getTime
  • getTimezoneOffset

As you can see, each method is fairly straightforward in the values it returns. The difference is in the value range returned. For example, the getDate method returns a numeric day of the month value ranging from 1 to 31; the getDay method returns a numeric day of the week value ranging from 0 to 6; the getHours method returns a numeric hour value ranging from 0 to 23; and the getMilliseconds function returns a numeric milliseconds value ranging from 0 to 999. The getMinutes and getSeconds methods return a value ranging from 0 and 59, and the getMonth method returns a numeric month value ranging from 0 to 11. The only unique methods in this list are getTime and getTimezoneOffset. The getTime method returns the number of milliseconds since 1/1/1970 at 12 a.m., while the getTimezoneOffset method returns the difference in minutes between GMT and local time.

For most of the getter methods, there is also a setter method that accepts a numeric argument in the corresponding value range. The setter methods are as follows:

  • setDate
  • setFullYear
  • setHours
  • setMilliseconds
  • setMinutes
  • setMonth
  • setSeconds
  • setTime

For all the getter methods listed above, there are matching methods that return the same value ranges, except that the values are set in universal time. These methods are:

  • getUTCDate
  • getUTCDay
  • getUTCFullYear
  • getUTCHours
  • getUTCMilliseconds
  • getUTCMinutes
  • getUTCMonth
  • getUTCSeconds

Of course, as there are setter methods for all of the original getter methods, there are also the same in universal time. These methods are:

  • setUTCDate
  • setUTCFullYear
  • setUTCHours
  • setUTCMilliseconds
  • setUTCMinutes
  • setUTCMonth
  • setUTCSeconds

As mentioned at the beginning of this article, I don't provide much information about the toString method, but there are a number of methods in the Date object that convert dates to a string and are worthy of mention. In some cases, it's necessary to convert a date or portion of a date into a string—for example, if you're appending it to a string or using it in a comparison statement. Several methods available to the Date object that provide slightly different methods that convert it to a string, including:

  • toDateString
  • toLocaleDateString
  • toLocaleTimeString
  • toLocaleString
  • toTimeString
  • toUTCString

The toDateString method converts a date to a string:

var myDate = new Date();
document.write(myDate.toDateString());

toDateString returns the current date in the format Tue Jul 19 2011.

The toTimeString method converts the time from the Date object it to a string:

var myDate = new Date();
document.write(myDate.toTimeString());

toTimeString returns the time as a string in the format 23:00:00 GMT-0700 (MST).

The final method that converts a date to a string is toUTCString, which converts a date to a string in universal time.

A few methods convert a date to a string using locale, but they are not supported by Google Chrome as the time of writing. The unsupported methods are toLocaleDateString, toLocaleTimeString, and toLocaleString.

The JavaScript Date object may seem simple at first glance, but it can be more than just a useful way to display the current date. It depends on the functionality you are inspired to create. For example, the Date object is the basis for creating a countdown ticker or any other time-related functionality.


Array

The JavaScript Array object is a variable on steroids: You use it to store multiple values in one variable at one time, and it has many methods that allow you to manipulate or gather information about the values it stores. Although the Array object doesn't discriminate about the value types, it's good practice to use the same type of values in a single array. So, for example, it's not good practice to use numbers and strings in the same array. All of the properties available to the Array object are read only, meaning that their value cannot be changed externally.

The only property available to the Array object is length. This property returns the number of elements in an array and is often used when iterating values in an array using a loop:

var myArray = new Array(1, 2, 3);
for(var i=0; i<myArray.length; i++) {
   document.write(myArray[i]);
}

A number of methods are available to the Array object, and you can use a variety of methods to add and remove elements to and from an array. These methods include pop, push, shift, and unshift. The pop and shift methods both remove elements from an array. The pop method removes and returns the last element in an array, while the shift method removes and returns the first element in an array. The opposite functionality can be achieved with the push and unshift methods, which add elements to an array. The push method adds elements to the end of an array as new elements and returns the new length, while the unshift method adds elements to the front of an array and returns the new length.

Sorting an array in JavaScript is possible with two methods, one of which is actually named sort. The other is reverse. The sort method is complex in that it sorts an array based on an optional sort function. The sort function can be any custom function that you write. The reverse method is not as complex as sort, although it does modify the order of the elements in an array by reversing them.

Indices are important when dealing with arrays, as they define the location of each and every element in an array. Two methods are able to alter a string based on an index: slice and splice. The slice method accepts an index or the combination of the starting and ending index as parameters, and then extracts and returns part of an array as a new array based on the arguments. The splice method includes index, length, and unlimited element parameters. The method adds elements to an array based on the specified index, removes elements from an array based on the specified index, or adds and removes elements to and from an array based on the specified index. There is also a method that can return an index based on a matching value: indexOf. You can then use this index to slice or splice an array.

The key to writing good code in any programming language is writing well-organized code. As you can see from its various methods, the JavaScript Array object is a powerful way to organize data and create complex functionality.


Math

The JavaScript Math object is used to perform mathematical functions. It cannot be instantiated: You simply use the Math object as is and call properties and methods from it without any instantiation:

var pi = Math.PI;

The Math object has many properties and methods that provide mathematical functionality to JavaScript. All of the Math properties are read-only constants and include the following:

  • E
  • LN2
  • LN10
  • LOG2E
  • LOG10E
  • PI
  • SQRT1_2
  • SQRT2

The E property returns the value of the base of natural logarithms, or Euler's number. This value is the unique real number, named after Leonhard Euler. Calling the E property results in the number 2.718281828459045. Two other properties are also used to return natural logarithms: LN2 and LN10. The LN2 property returns the value of the natural logarithm of 2, while the LN10 property returns the value of the natural logarithm of 10. The LOG2E and LOG10E properties could be used to return the base-2 or base-10 logarithm of E. The result of LOG2E is 1.4426950408889633, while the result of LOG10E is 0.4342944819032518. You won't need most of these properties often, unless of course you are building a calculator or other math-intensive project. However, PI and square root are a bit more common. The PI method returns the ratio of a circles circumference to its diameter. Two properties return square root values: SQRT1_2 and SQRT2. The first returns the square root of 0.5, while SQRT2 returns the square root of 2.

In addition to these properties, there are several methods that you can use to return different values of a number. Each of these methods accepts numeric values and returns a value based on the method name. Unfortunately, the method names are not always self-explanatory:

  • abs. The absolute value of a number
  • acos. Arccosine
  • asin. Arcsine
  • atan. Arctangent
  • atan2. The arctangent of multiple numbers
  • cos. Cosine
  • exp. Ex
  • log. A number's natural logarithm
  • pow. The value of x to the power of y
  • sin. Sine
  • sqrt. Square root
  • tan. The tangent of an angle

Three methods can be used to round numbers in JavaScript: ceil, floor, and round. The ceil method returns a number's upward-rounded value. This method is useful when you need to round a number up to the nearest whole number. The floor method provides the opposite functionality of ceil: It returns the downward-rounded value of a number. This method is useful when you need to round a number down to the nearest whole number. The round method provides normal rounding functionality, rounding a number up or down based on any existing decimals.

The final three methods included in the Math object are max, min, and random. The max method accepts multiple numeric arguments and returns the highest value, while the min method accepts multiple numeric arguments and returns the lowest value. These methods can be useful when comparing variables that have numeric values, especially when you do not already know what the numeric values are. You use the random method to return a random number between 0 and 1. You can use this method for many reasons, such as displaying a random image on the home page of a website or to return a random number that could be used as an index for an array that contained file paths for images. The random image file path that was selected from the array could then be used to write that image to an HTML <img> tag.


Conclusion

The properties and methods that JavaScript provides are just the beginning of the functionality that's possible: It's your imagination that creates custom functionality. As your imagination has no boundaries, neither should the code you write. JavaScript is a flexible language, which sometimes gives it a bad name; but on the bright side, it also provides you with the ability to quickly and creatively write code. To learn more about JavaScript objects and how to create your own custom objects using the JavaScript language, be sure to check out the Resources section.

Resources

Learn

Get products and technologies

  • Try out IBM software for free. Download a trial version, log into an online trial, work with a product in a sandbox environment, or access it through the cloud. Choose from over 100 IBM product trials.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=749047
ArticleTitle=Understanding built-in objects in JavaScript
publish-date=08162011