Chapter 8. Objects

Chapter 3 explained that objects are one of the fundamental data types in JavaScript. They are also one of the most important. This chapter describes JavaScript objects in detail. Basic usage of objects, described in the next section, is straightforward, but as we’ll see in later sections, objects have more complex uses and behaviors.

Objects and Properties

Objects are composite data types: they aggregate multiple values into a single unit and allow us to store and retrieve those values by name. Another way to explain this is to say that an object is an unordered collection of properties, each of which has a name and a value. The named values held by an object may be primitive values like numbers and strings, or they may themselves be objects.

Creating Objects

Objects are created with the new operator. This operator must be followed by the name of a constructor function that serves to initialize the object. For example, we can create an empty object (an object with no properties) like this:

var o = new Object(  );

JavaScript supports other built-in constructor functions that initialize newly created objects in other, less trivial, ways. For example, the Date( ) constructor initializes an object that represents a date and time:

var now = new Date(  );                        // The current date and time
var new_years_eve = new Date(2000, 11, 31);  // Represents December 31, 2000

Later in this chapter, we’ll see that it is possible to define custom constructor methods to initialize ...

Get JavaScript: The Definitive Guide, Fourth Edition 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.