Objects as Associative Arrays

We’ve seen the . operator used to access the properties of an object. It is also possible to use the [] operator, which is more commonly used with arrays, to access these properties. Thus, the following two JavaScript expressions have the same value:

object.property
object["property"]

The important difference to note between these two syntaxes is that in the first, the property name is an identifier, and in the second, the property name is a string. We’ll see why this is so important shortly.

In C, C++, Java, and similar strongly typed languages, an object can have only a fixed number of properties, and the names of these properties must be defined in advance. Since JavaScript is a loosely typed language, this rule does not apply -- a program can create any number of properties in any object. When you use the . operator to access a property of an object, however, the name of the property is expressed as an identifier. Identifiers must be typed literally into your JavaScript program -- they are not a data type, so they cannot be manipulated by the program.

On the other hand, when you access a property of an object with the [] array notation, the name of the property is expressed as a string. Strings are JavaScript data types, so they can be manipulated and created while a program is running. So, for example, you could write the following code in JavaScript:

var addr = "";
for(i = 0; i < 4; i++) {
    addr += customer["address" + i] + '\n';
}

This ...

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.