Nested Objects

In JavaScript, objects can contain other objects as properties. These are called nested objects. This allows you to represent complex data structures in a natural way.

Accessing Nested Objects

You access properties inside nested objects by chaining the dot notation or bracket notation.

📌 Deep Dive: Accessing Nested Properties

JAVASCRIPT
const user = {
  name: "Alice",
  address: {
    city: "Wonderland",
    zip: "12345"
  }
};

console.log(user.address.city);  // Wonderland
console.log(user["address"]["zip"]);  // 12345
Output
Wonderland
12345

Modifying Nested Objects

You can update or add properties inside nested objects the same way you do for top-level properties.

📌 Deep Dive: Modifying Nested Properties

JAVASCRIPT
user.address.street = "Rabbit Hole Rd";
user.address.city = "New Wonderland";

console.log(user.address.street);  // Rabbit Hole Rd
console.log(user.address.city);    // New Wonderland
Output
Rabbit Hole Rd
New Wonderland
Illustration of nested_objects
Illustration of nested_objects

💡 Important

If you try to access a nested property that does not exist, the result will be undefined. Accessing deeper levels on an undefined value will cause an error.

⚠️ Watch Out

Always verify nested properties exist before accessing them to avoid runtime errors. Optional chaining (e.g., obj?.prop?.subprop) can help safely access nested data.

Use Cases for Nested Objects

  • Representing structured data like user profiles, configuration settings, or API responses.
  • Grouping related information logically inside a single object.
  • Organizing data hierarchically for easier access and modification.
Access Notation Comparison
NotationExample
Dot Notationuser.address.city
Bracket Notationuser["address"]["city"]