0
0
Javascriptprogramming~5 mins

Instance methods in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Instance methods
O(n)
Understanding Time Complexity

Let's see how the time it takes to run instance methods changes as we use more data.

We want to know how the work grows when calling methods on objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Counter {
  constructor() {
    this.count = 0;
  }
  increment() {
    this.count += 1;
  }
  incrementBy(n) {
    for (let i = 0; i < n; i++) {
      this.increment();
    }
  }
}
    

This code defines a class with methods to increase a count, either by 1 or by a given number.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop inside incrementBy calls increment repeatedly.
  • How many times: The loop runs n times, where n is the input to incrementBy.
How Execution Grows With Input

Each time we increase n, the loop runs that many times, so the work grows directly with n.

Input Size (n)Approx. Operations
1010 calls to increment
100100 calls to increment
10001000 calls to increment

Pattern observation: The number of operations grows evenly as n grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to run incrementBy grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Calling increment inside the loop makes it slower than linear time."

[OK] Correct: Each increment call is simple and constant time, so repeating it n times still grows linearly.

Interview Connect

Understanding how instance methods run helps you explain how your code scales when working with objects and their data.

Self-Check

"What if incrementBy called increment twice inside the loop? How would the time complexity change?"