0
0
Javascriptprogramming~5 mins

Iterating over objects in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Iterating over objects
O(n)
Understanding Time Complexity

When we loop through all the properties of an object, the time it takes depends on how many properties there are.

We want to know how the work grows as the object gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const obj = {a: 1, b: 2, c: 3};
for (const key in obj) {
  console.log(key, obj[key]);
}
    

This code goes through each property in the object and prints its key and value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for...in loop that visits each property in the object.
  • How many times: Once for every property in the object.
How Execution Grows With Input

As the number of properties grows, the loop runs more times, doing more work.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The work grows directly with the number of properties. Double the properties, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of properties in the object.

Common Mistake

[X] Wrong: "Looping over an object is always constant time because objects are fast."

[OK] Correct: The loop visits every property, so if the object has more properties, it takes more time.

Interview Connect

Understanding how looping over objects scales helps you write efficient code and answer questions about performance clearly.

Self-Check

"What if we used Object.keys(obj).forEach() instead of for...in? How would the time complexity change?"