0
0
Javascriptprogramming~5 mins

Constructor functions in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constructor functions
O(n)
Understanding Time Complexity

Let's see how the time it takes to create objects with constructor functions changes as we make more objects.

We want to know how the work grows when making many objects using a constructor.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log(`Hi, I am ${this.name}`);
  };
}

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

This code creates n person objects using a constructor function and stores them in an array.

Identify Repeating Operations
  • Primary operation: Creating a new Person object inside the loop.
  • How many times: The loop runs n times, so the constructor runs n times.
How Execution Grows With Input

Each time we add one more person, the work grows by one constructor call.

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

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

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of objects, the time to create them roughly doubles too.

Common Mistake

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

[OK] Correct: Each object needs time to be created, so more objects mean more time spent.

Interview Connect

Understanding how object creation scales helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

"What if the constructor function included a loop inside it? How would that affect the time complexity when creating n objects?"