Adding and removing properties in Javascript - Time & Space Complexity
We want to understand how the time it takes to add or remove properties from an object changes as the object grows.
How does the number of properties affect the speed of these operations?
Analyze the time complexity of the following code snippet.
const obj = {};
// Adding properties
for (let i = 0; i < n; i++) {
obj['key' + i] = i;
}
// Removing properties
for (let i = 0; i < n; i++) {
delete obj['key' + i];
}
This code adds n properties to an object, then removes those n properties one by one.
- Primary operation: Adding and deleting properties inside loops.
- How many times: Each loop runs n times, performing one add or delete per iteration.
As n grows, the number of add and delete operations grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 adds + 10 deletes) |
| 100 | About 200 (100 adds + 100 deletes) |
| 1000 | About 2000 (1000 adds + 1000 deletes) |
Pattern observation: The total work grows in a straight line as n increases.
Time Complexity: O(n)
This means the time to add and remove properties grows directly in proportion to the number of properties.
[X] Wrong: "Adding or removing a property takes the same time no matter how many properties the object has."
[OK] Correct: While each add or delete is fast, doing many of them adds up, so total time grows with the number of operations.
Understanding how simple operations like adding or removing properties scale helps you reason about object manipulation performance in real projects.
"What if we added properties in a nested loop instead? How would the time complexity change?"