Iterating over objects in Javascript - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
for...inloop that visits each property in the object. - How many times: Once for every property in the object.
As the number of properties grows, the loop runs more times, doing more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the number of properties. Double the properties, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of properties in the object.
[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.
Understanding how looping over objects scales helps you write efficient code and answer questions about performance clearly.
"What if we used Object.keys(obj).forEach() instead of for...in? How would the time complexity change?"