Chapter 7. Objects and Arrays

Chapter 3, explained that objects and arrays are two fundamental datatypes in JavaScript. They are also two of the most important. Objects and arrays differ from primitive datatypes such as strings and numbers: instead of representing a single value, they are instead collections of values. An object is a collection of named values, and an array is a specialized kind of object that behaves as an ordered collection of numbered values. This chapter describes JavaScript objects and arrays in detail.

Creating Objects

Objects are composite datatypes: they aggregate multiple values into a single unit and allow you 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, such as numbers and strings, or they may themselves be objects.

The easiest way to create an object is to include an object literal in your JavaScript code. An object literal is a comma-separated list of property name/value pairs, enclosed within curly braces. Each property name can be a JavaScript identifier or a string, and each property value can be a constant or any JavaScript expression. Here are some examples:

var empty = {}; // An object with no properties var point = { x:0, y:0 }; var circle = { x:point.x, y:point.y+1, radius:2 }; var homer = { "name": "Homer Simpson", "age": 34, "married": true, "occupation": ...

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