Nested objects in Javascript - Time & Space Complexity
When working with nested objects, it is important to understand how the time to access or process data grows as the object gets bigger.
We want to know how the number of steps changes when the nested objects have more keys or levels.
Analyze the time complexity of the following code snippet.
const data = {
user: {
name: 'Alice',
address: { city: 'Wonderland', zip: 12345 }
},
orders: [ { id: 1 }, { id: 2 } ]
};
function printUserCity(obj) {
console.log(obj.user.address.city);
}
printUserCity(data);
This code accesses a nested property inside an object and prints it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing nested keys step-by-step.
- How many times: Each key access happens once in sequence.
Accessing nested keys takes one step per level, so if the nesting grows deeper, the steps grow linearly with depth.
| Input Size (nesting depth) | Approx. Operations |
|---|---|
| 3 | 3 steps (user → address → city) |
| 5 | 5 steps (5 nested keys) |
| 10 | 10 steps (10 nested keys) |
Pattern observation: The number of steps grows directly with how deep the object is nested.
Time Complexity: O(n)
This means the time to access a nested value grows linearly with the depth of the nesting.
[X] Wrong: "Accessing nested objects is always constant time because it's just property access."
[OK] Correct: Each nested key access happens one after another, so deeper nesting means more steps, not always instant.
Understanding how nested object access scales helps you reason about data structures and performance in real projects.
"What if we added a loop to process all keys at each nesting level? How would the time complexity change?"