0
0
Javascriptprogramming~5 mins

Nested objects in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested objects
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
33 steps (user → address → city)
55 steps (5 nested keys)
1010 steps (10 nested keys)

Pattern observation: The number of steps grows directly with how deep the object is nested.

Final Time Complexity

Time Complexity: O(n)

This means the time to access a nested value grows linearly with the depth of the nesting.

Common Mistake

[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.

Interview Connect

Understanding how nested object access scales helps you reason about data structures and performance in real projects.

Self-Check

"What if we added a loop to process all keys at each nesting level? How would the time complexity change?"