0
0
Javascriptprogramming~5 mins

Class syntax in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Class syntax
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code using JavaScript classes changes as we create more objects or call methods.

We want to know how the work grows when using class syntax for multiple objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Counter {
  constructor() {
    this.count = 0;
  }
  increment() {
    this.count++;
  }
}

const counters = [];
for (let i = 0; i < n; i++) {
  counters.push(new Counter());
}

This code creates n Counter objects, each starting with a count of zero.

Identify Repeating Operations
  • Primary operation: Creating a new Counter object inside a loop.
  • How many times: The loop runs n times, creating n objects.
How Execution Grows With Input

Each time we increase n, we create more objects, so the work grows directly with n.

Input Size (n)Approx. Operations
1010 object creations
100100 object creations
10001000 object creations

Pattern observation: The work grows evenly as we add more objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all objects grows in a straight line as we add more objects.

Common Mistake

[X] Wrong: "Creating objects inside a loop is instant and does not depend on how many objects we make."

[OK] Correct: Each object takes some time to create, so more objects mean more total time.

Interview Connect

Understanding how creating many objects affects time helps you write efficient code and explain your choices clearly.

Self-Check

"What if the increment method was called inside the loop for each object? How would the time complexity change?"