Constructors in classes in Javascript - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that createsnPerson objects. - How many times: The constructor runs once for each of the
niterations.
Each new object takes a small fixed amount of work to set properties.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 constructor calls |
| 100 | About 100 constructor calls |
| 1000 | About 1000 constructor calls |
Pattern observation: The work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line as you add more objects.
[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.
Understanding how constructors scale helps you explain object creation costs clearly and confidently in real coding situations.
What if the constructor included a loop that runs m times inside it? How would the time complexity change?