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?
Practice
constructor in a JavaScript class?Solution
Step 1: Understand the role of a constructor
A constructor is a special method in a class that runs automatically when a new object is created.Step 2: Identify what constructors do
Constructors set initial values for the object's properties usingthis.Final Answer:
To initialize new objects with default or given values -> Option CQuick Check:
Constructor = initialize object [OK]
- Confusing constructors with regular methods
- Thinking constructors delete objects
- Believing constructors create static properties
Solution
Step 1: Recall JavaScript class constructor syntax
In JavaScript classes, the constructor is defined as a method namedconstructorwithout thefunctionkeyword.Step 2: Check each option
constructor() { this.name = 'John'; } uses the correct syntax:constructor() { ... }. Options B and C incorrectly use keywords from other languages or function syntax. constructor = () => { this.name = 'John'; } uses arrow function syntax, which is invalid for constructors.Final Answer:
constructor() { this.name = 'John'; } -> Option AQuick Check:
Constructor method = constructor() { } [OK]
- Adding 'function' keyword before constructor
- Using arrow functions for constructors
- Using other language syntax like 'def'
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const p = new Person('Alice');
console.log(p.greet());Solution
Step 1: Understand object creation with constructor
ThePersonclass constructor setsthis.nameto the passed argument. Here, 'Alice' is passed, sop.namebecomes 'Alice'.Step 2: Evaluate the greet method output
Thegreetmethod returns a string usingthis.name, which is 'Alice'. So,p.greet()returns 'Hello, Alice!'.Final Answer:
Hello, Alice! -> Option BQuick Check:
Constructor sets name, greet uses it = Hello, Alice! [OK]
- Forgetting to pass argument to constructor
- Expecting undefined because of missing this
- Thinking greet is not a method
class Car {
constructor(make, model) {
make = make;
model = model;
}
}Solution
Step 1: Review property assignment in constructor
Inside a constructor, to assign values to the object's properties, you must usethis.propertyName. Simply writingmake = make;assigns the parameter to itself, which does nothing.Step 2: Identify the correct fix
Usingthis.make = make;andthis.model = model;correctly assigns the values to the new object's properties.Final Answer:
Properties should be assigned usingthis, likethis.make = make;-> Option AQuick Check:
Use this.property = parameter [OK]
- Assigning parameters to themselves
- Not using this to set properties
- Thinking constructor must return explicitly
Book class where each book has a title and an optional author. If no author is given, it should default to 'Unknown'. Which constructor correctly implements this behavior?Solution
Step 1: Understand optional parameters in constructors
Use default parameter values for optional arguments. constructor(title, author = 'Unknown') { this.title = title; this.author = author; }:constructor(title, author = 'Unknown')sets author to 'Unknown' if not provided or undefined, but keeps passed falsy values like empty string.Step 2: Check other options
B uses||, which defaults falsy values (not just missing). C has no author param. D sets only if truthy, else undefined.Final Answer:
constructor(title, author = 'Unknown') { this.title = title; this.author = author; } -> Option DQuick Check:
Optional param: param = default [OK]
- Using logical OR (||) which treats falsy as missing
- Omitting the optional parameter entirely
- Not providing a default, leaving undefined
Ready to prove it?
Pass the test and this pattern moves unknown
