20.8. Objects

JavaScript is an object-driven language. As you will see in Chapter 21, "The Document Object Model," the user agent supplies a host of objects that your scripts can reference. However, you will encounter many objects built into JavaScript that are outside of the Document Object Model.

20.8.1. Built-in Objects

JavaScript has several built-in objects. For example, two specific objects exist for manipulating data: one for performing math operations (Math) on numeric data and another for performing operations on string values (String).

These objects have various methods for acting upon data. For example, to find the square root of variable x, you could use the Math.sqrt method:

x = Math.sqrt(x);  // square root of x

Or, to convert a string to lowercase, you could use the String.toLowerCase() method:

s = String.toLowerCase(s);  // convert s to lowercase

As with most object-oriented languages, JavaScript supports the with statement. Using the with statement can facilitate using multiple methods of the same object, as shown in the following code:

with (Math) {
y = random(200);
x = round(sqrt(y));
}

The same code without using the with statement would look like the following code:

y = Math.random(200);
x = Math.round(Math.sqrt(y));

Although the Math object was referenced only three times in the code, you can see how repeatedly referencing the object could get tedious when constructing complex mathematical operations.

Another very useful object is the Date object. This object ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.