JavaScript Fundamentals / Objects

Nested Objects

🔹 What are Nested Objects?

A nested object is when an object contains another object as one of its property values.

const myObj = {
  name: "John",
  age: 30,
  myCars: {
    car1: "Ford",
    car2: "BMW",
    car3: "Fiat"
  }
};

Here:

  • myObj is the main object.

  • myCars is a nested object inside myObj.

  • myCars contains three properties: car1, car2, and car3.


🔸How to Access Nested Properties

1. Dot Notation

console.log(myObj.myCars.car2); // Output: BMW
  • This is the most common and clean way to access nested properties.

  • You go level by level: myObj → myCars → car2.


2. Bracket Notation

console.log(myObj.myCars["car2"]); // Output: BMW
console.log(myObj["myCars"]["car2"]); // Output: BMW

Bracket notation is useful when:

  • The property name is dynamic (from a variable).

  • The property name contains spaces or special characters.


3. Using Variables as Keys

let p1 = "myCars";
let p2 = "car2";

console.log(myObj[p1][p2]); // Output: BMW
  • This is how you access nested properties dynamically using variables.

  • p1 holds "myCars" and p2 holds "car2", so myObj[p1][p2] = myObj["myCars"]["car2"].


🧠 Why Use Nested Objects?

Nested objects are useful to:

  • Represent complex data structures.

  • Organize related data together (e.g., user profile, car details, settings).