0
0
Javascriptprogramming~5 mins

Adding and removing properties in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Adding and removing properties
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Adding and deleting properties inside loops.
  • How many times: Each loop runs n times, performing one add or delete per iteration.
How Execution Grows With Input

As n grows, the number of add and delete operations grows directly with n.

Input Size (n)Approx. Operations
10About 20 (10 adds + 10 deletes)
100About 200 (100 adds + 100 deletes)
1000About 2000 (1000 adds + 1000 deletes)

Pattern observation: The total work grows in a straight line as n increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to add and remove properties grows directly in proportion to the number of properties.

Common Mistake

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

Interview Connect

Understanding how simple operations like adding or removing properties scale helps you reason about object manipulation performance in real projects.

Self-Check

"What if we added properties in a nested loop instead? How would the time complexity change?"