Nested Objects

Nested objects are objects within other objects. Let's start by reviewing a basic object:

var president = {
  firstName: "Barack",
  lastName: "Obama"
}

president.firstName; // "Barack"
president.lastName; // "Obama"

The president's wife can be modeled as a nested object.

var president = {
  firstName: "Barack",
  lastName: "Obama",
  wife: {
    firstName: "Michelle",
    lastName: "Obama",
    birthYear: 1964
  }
}

president.wife.firstName; // "Michelle"
president.wife.birthYear; // 1964

Nested objects can be used to model the real world and are used extensively.

Here is another way to write the president object and get the same result:

var firstLady = {
  firstName: "Michelle",
  lastName: "Obama",
  birthYear: 1964
}

var president = {
  firstName: "Barack",
  lastName: "Obama",
  wife: firstLady
}

president.wife.firstName; // "Michelle"
president.wife.birthYear; // 1964
firstLady.birthYear; // 1964
Question Click to View Answer

What does the following code print to the console?

var billGates = {
  firstName: "Bill",
  lastName: "Gates",
  address: {
    state: "Washington",
    city: "Medina"
  }
}
console.log(billGates.address.state);

Washington

The billGates object has an address property that points to another object (the nested object).

var olympics = {
  headquarters: "Switzerland",
  records: {
    countryWithMostMetals: "United States",
    personWithMostMetals: "Michael Phelps"
  }
}

console.log(olympics.headquarters);

Switzerland

var bob = {
  age: 39,
  favoriteSport: "basketball"
}

var cindy = {
  age: 12,
  favoriteSport: "cricket",
  father: bob
}

console.log(cindy.father.favoriteSport);

basketball

The bob object is nested in the cindy object (bob is cindy's father). bob's favorite sport is basketball.

<-- Previous (Nested Arrays) Next (Arrays of Objects) -->