Constructor functions in Javascript - Time & Space 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.
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.
- Primary operation: Creating a new
Personobject inside the loop. - How many times: The loop runs
ntimes, so the constructor runsntimes.
Each time we add one more person, the work grows by one constructor call.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 constructor calls |
| 100 | 100 constructor calls |
| 1000 | 1000 constructor calls |
Pattern observation: The work grows directly with the number of objects created.
Time Complexity: O(n)
This means if you double the number of objects, the time to create them roughly doubles too.
[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.
Understanding how object creation scales helps you write efficient code and explain your reasoning clearly in interviews.
"What if the constructor function included a loop inside it? How would that affect the time complexity when creating n objects?"
Practice
new keyword do when used with a constructor function in JavaScript?Solution
Step 1: Understand the role of
Thenewnewkeyword creates a fresh object and setsthisinside the constructor to that object.Step 2: Effect on constructor function
It allows the constructor to initialize properties on the new object and then returns it automatically.Final Answer:
Creates a new object and setsthisto that object inside the constructor -> Option AQuick Check:
newcreates object = A [OK]
new makes a new object and sets this [OK]- Thinking
newjust calls the function without creating an object - Believing
newreturns a string - Confusing
newwith deleting functions
Car?Solution
Step 1: Identify valid constructor function syntax
A constructor function is a normal function with a capitalized name, likefunction Car() {}.Step 2: Check each option
function Car() { this.make = 'Toyota'; } uses correct function syntax. var Car = () => { this.make = 'Toyota'; } uses arrow function which does not bindthisproperly. class Car { make = 'Toyota'; } is a class, not a constructor function. function Car[] { this.make = 'Toyota'; } has invalid syntax with square brackets.Final Answer:
function Car() { this.make = 'Toyota'; } -> Option AQuick Check:
Constructor function = normal function with capital name [OK]
- Using arrow functions as constructors
- Trying to use class syntax instead of function
- Writing invalid function syntax with brackets
function Person(name) {
this.name = name;
}
const p = new Person('Alice');
console.log(p.name);Solution
Step 1: Understand object creation with constructor
Thenew Person('Alice')creates a new object and setsthis.nameto 'Alice'.Step 2: Access the property
Loggingp.nameprints the value assigned, which is 'Alice'.Final Answer:
Alice -> Option CQuick Check:
Property set by constructor = 'Alice' [OK]
this.name sets property on new object [OK]- Expecting undefined because of missing return
- Confusing constructor name with property value
- Thinking
console.logprints function name
function Animal(type) {
type = type;
this.type = type;
}
const a = new Animal('Dog');
console.log(a.type);Solution
Step 1: Analyze the assignment
This line assigns the parametertype = type;typeto itself, which does nothing and is unnecessary.Step 2: Check other parts
The linethis.type = type;correctly assigns the parameter to the object property. Thenewkeyword is used correctly. Function name capitalization is fine.Final Answer:
The assignmenttype = type;does nothing and is redundant -> Option DQuick Check:
Redundant self-assignment = B [OK]
- Thinking
type = type;sets object property - Forgetting to use
newkeyword - Believing constructor names must be lowercase
Book that takes title and author as parameters and adds a method describe that returns a string like "Title by Author". Which code correctly does this?Solution
Step 1: Check method definition inside constructor
function Book(title, author) { this.title = title; this.author = author; this.describe = function() { return `${this.title} by ${this.author}`; }; } correctly definesdescribeas a function property onthis, so each object has its own method.Step 2: Analyze other options
function Book(title, author) { this.title = title; this.author = author; } Book.describe = function() { return `${this.title} by ${this.author}`; }; addsdescribeto the constructor function itself, not instances. function Book(title, author) { this.title = title; this.author = author; describe() { return `${this.title} by ${this.author}`; } } has invalid syntax for method inside function. function Book(title, author) { this.title = title; this.author = author; this.describe = `${this.title} by ${this.author}`; } assigns a string, not a function, sodescribeis not callable.Final Answer:
function Book(title, author) { this.title = title; this.author = author; this.describe = function() { return `${this.title} by ${this.author}`; }; } -> Option BQuick Check:
Method as function property onthis= A [OK]
this inside constructor [OK]- Adding methods to constructor function instead of instances
- Using invalid syntax for methods inside functions
- Assigning method as string instead of function
Ready to prove it?
Pass the test and this pattern moves unknown
