0
0
Javascriptprogramming~5 mins

Constructors in classes in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constructors in classes
O(n)
Understanding Time Complexity

Let's see how the time it takes to run a constructor in a class changes as we create more objects.

We want to know how the work done inside the constructor grows when we make many instances.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const people = [];
for (let i = 0; i < n; i++) {
  people.push(new Person(`Name${i}`, i));
}
    

This code creates n Person objects, each with a name and age set by the constructor.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop that creates n Person objects.
  • How many times: The constructor runs once for each of the n iterations.
How Execution Grows With Input

Each new object takes a small fixed amount of work to set properties.

Input Size (n)Approx. Operations
10About 10 constructor calls
100About 100 constructor calls
1000About 1000 constructor calls

Pattern observation: The work grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The constructor runs only once no matter how many objects are created."

[OK] Correct: Each object needs its own constructor call to set up its properties, so the constructor runs once per object.

Interview Connect

Understanding how constructors scale helps you explain object creation costs clearly and confidently in real coding situations.

Self-Check

What if the constructor included a loop that runs m times inside it? How would the time complexity change?