Object use cases in Javascript - Time & Space Complexity
When using objects in JavaScript, it's important to know how fast operations like adding, accessing, or checking properties happen.
We want to understand how the time to do these tasks changes as the object grows bigger.
Analyze the time complexity of the following code snippet.
const obj = {};
for (let i = 0; i < n; i++) {
obj[`key${i}`] = i;
}
const value = obj['key500'];
const hasKey = 'key500' in obj;
This code adds n properties to an object, then accesses and checks one property.
- Primary operation: Adding properties inside a loop.
- How many times: n times, once per loop iteration.
- Accessing and checking a property happens once each, outside the loop.
Adding properties grows with the number of items n, but accessing or checking a property stays quick no matter the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions, 1 access, 1 check |
| 100 | 100 additions, 1 access, 1 check |
| 1000 | 1000 additions, 1 access, 1 check |
Pattern observation: Adding properties grows linearly with n, but accessing or checking a property stays constant time.
Time Complexity: O(n)
This means adding n properties takes time proportional to n, but accessing or checking a property is very fast and does not depend on n.
[X] Wrong: "Accessing a property in an object takes longer as the object gets bigger."
[OK] Correct: Objects use a special way to find properties quickly, so access time stays about the same no matter how many properties there are.
Understanding how objects work behind the scenes helps you write faster code and answer questions about efficiency with confidence.
"What if we used an array instead of an object to store these key-value pairs? How would the time complexity change?"