0
0
Javascriptprogramming~5 mins

Object use cases in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Object use cases
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

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
1010 additions, 1 access, 1 check
100100 additions, 1 access, 1 check
10001000 additions, 1 access, 1 check

Pattern observation: Adding properties grows linearly with n, but accessing or checking a property stays constant time.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how objects work behind the scenes helps you write faster code and answer questions about efficiency with confidence.

Self-Check

"What if we used an array instead of an object to store these key-value pairs? How would the time complexity change?"