0
0
Javascriptprogramming~5 mins

Inheritance using classes in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Inheritance using classes
O(n)
Understanding Time Complexity

When using inheritance with classes, we want to know how the program's work grows as we create more objects or call methods.

We ask: How does the time to run change when we use inherited methods or create many instances?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Animal {
  speak() {
    console.log('Animal speaks');
  }
}

class Dog extends Animal {
  speak() {
    super.speak();
    console.log('Dog barks');
  }
}

const dog = new Dog();
dog.speak();
    

This code shows a Dog class inheriting from Animal and calling the parent method before adding its own behavior.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the speak method on the Dog instance.
  • How many times: Once per call; no loops or recursion inside the methods.
How Execution Grows With Input

Each time we call speak, it runs a fixed number of steps: one call to the parent method and one extra log.

Input Size (n)Approx. Operations
12 (one parent call + one child log)
1020 (10 calls x 2 operations each)
100200 (100 calls x 2 operations each)

Pattern observation: The work grows directly with how many times we call the method, staying simple and linear.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of method calls; each call takes a fixed amount of work.

Common Mistake

[X] Wrong: "Inheritance makes method calls slower exponentially because of chaining."

[OK] Correct: Each inherited method call adds only a fixed small number of steps, so time grows linearly, not exponentially.

Interview Connect

Understanding how inheritance affects time helps you explain code efficiency clearly and shows you know how objects work behind the scenes.

Self-Check

"What if the speak method called itself recursively? How would the time complexity change?"