Nested Objects
You'll learn: How to store objects inside other objects and retrieve values from multiple layers deep.
What Are Nested Objects?
Just like folders on your computer can contain other folders, objects in JavaScript can contain other objects as property values. This creates a hierarchy or "tree" of data that mirrors real-world relationships.
Think of a student record: a student has basic info (name, age) and an address. That address itself has multiple parts (street, city, zip). Rather than flatten everything, you nest the address object inside the student object.
Creating Nested Objects
You simply assign an object literal as a property value:
const student = {
name: "Alex",
age: 20,
address: {
street: "123 Main St",
city: "Boston",
zip: "02101"
}
};
Here, address is a property whose value is another object.
Accessing Nested Properties
Chain dot notation to drill down:
console.log(student.name); // "Alex"
console.log(student.address); // { street: "123 Main St", ... }
console.log(student.address.city); // "Boston"
Or mix bracket notation:
console.log(student["address"]["zip"]); // "02101"
Multiple Levels
You can nest as deeply as needed:
const company = {
name: "TechCo",
ceo: {
name: "Jane Doe",
contact: {
email: "jane@techco.com",
phone: "555-1234"
}
}
};
console.log(company.ceo.contact.email); // "jane@techco.com"
Key Takeaway: Objects can contain other objects, creating structured data hierarchies accessed by chaining property lookups.