Review: Using JavaScript Objects

Bracket notation

Bracket notation provides an alternative way to access object properties. Instead of using dot notation like this:

person.age;
person.name.first;

You can instead use brackets:

person["age"];
person["name"]["first"];

This looks very similar to how you access the items in an array, and it is the same thing - instead of using an index number to select an item, you are using the name associated with each member's value. It is no wonder that objects are sometimes called associative arrays - they map strings to values in the same way that arrays map numbers to values.

Dot notation is generally preferred over bracket notation because it is more succinct and easier to read. However, there are some cases where you have to use brackets. For example, if an object property name is held in a variable, you can not use dot notation to access the value, but you can use bracket notation.

In the example below, the logProperty() function can use person[propertyName] to retrieve the value of the property named in propertyName.

const person = {
  name: ["Bob", "Smith"],
  age: 32,
};

function logProperty(propertyName) {
  console.log(person[propertyName]);
}

logProperty("name");
// ["Bob", "Smith"]
logProperty("age");
// 32