Lesson 32: Mastering JavaScript Constructor Functions and the new Operator with challenges!

A constructor function in JavaScript is used to create multiple instances of similar objects. When invoked with the new
operator, the function:
Creates a new empty object.
Sets
this
to point to that object.Executes the function body.
Returns the object
this
(unless it returns another object explicitly).
โ Syntax
function User(name) {
this.name = name;
this.isAdmin = false;
}
let user1 = new User("Alice");
let user2 = new User("Bob");
Both user1
and user2
now have the same structure but different values.
๐ Visual Flowchart
new User("Alice") โก
Step 1: Create empty object โ {}
Step 2: Set `this` to the new object
Step 3: Execute User function โ this.name = "Alice"
Step 4: Return the object โ { name: "Alice", isAdmin: false }
Real-World Example
function Product(name, price) {
this.name = name;
this.price = price;
this.discount = function(percent) {
return this.price * (1 - percent / 100);
};
}
let phone = new Product("iPhone", 1200);
console.log(phone.discount(10)); // 1080
๐น 2. Fill Any Gaps
๐ธ Common Misconceptions
Arrow functions cannot be used as constructors (
TypeError: Class constructor can't be invoked without 'new'
)Forgetting
new
leads tothis
pointing towindow
orundefined
in strict mode.Returning an object overrides the default
this
.
๐ธ Edge Cases
function Person(name) {
this.name = name;
return { custom: "object" }; // overrides the `this` return
}
let p = new Person("Tom");
console.log(p.name); // undefined
console.log(p.custom); // object
๐ธ new.target
Helpful for ensuring a constructor is called properly:
function ForceNew(name) {
if (!new.target) return new ForceNew(name);
this.name = name;
}
๐ธ Performance Trap
Methods defined inside the constructor are recreated per instance, unlike prototypes:
function Car() {
this.drive = function() {}; // bad for memory if many instances
}
๐น 3. Challenge Me Deeply
๐ข Basic
Create a
Book
constructor withtitle
andauthor
.Make a
Circle
constructor that calculates area.Create a
Dog
constructor withbark()
method.
๐ก Intermediate
Add a prototype method to a constructor to reduce memory usage.
Use
new.target
to enforce use ofnew
.Write a constructor that returns a different object conditionally.
๐ด Advanced
Create a singleton with a constructor.
Simulate
new
behavior manually with a function.Create a
Timer
constructor that tracks elapsed time.Make a constructor chain (e.g.,
Admin
extendsUser
) without using classes.
๐ฏ Brain Twister
- Write a constructor that creates only one instance for any given name (a basic flyweight pattern).
๐น 4. Interview-Ready Questions
โ Conceptual
What does the
new
keyword do behind the scenes?Can every function be a constructor?
โ Scenario-Based
You have a constructor that must behave correctly with and without
new
. How would you design it?How would you make sure that methods aren't redefined for every instance?
โ Debugging
function Robot(name) {
this.name = name;
return "Not a robot";
}
let rob = new Robot("Wall-E");
console.log(rob.name); // ???
โ Best Practices
โ
Use prototypes for methods
โ
Name constructors with PascalCase
๐ซ Avoid redefining methods inside the constructor
๐ซ Donโt forget new
๐น 5. Real-World Usage
DOM wrappers: Like
new XMLHttpRequest()
Frameworks: React components before hooks were class-based (
class extends React.Component
)Custom Error Types:
function ValidationError(message) { this.message = message; this.name = "ValidationError"; }
๐น 6. Remember Like a Pro
Mnemonic:
"NEW helps me create something NEW!"
Cheatsheet:
Rule | Result |
Constructor returns object? | That object is returned |
Constructor returns primitive? | Ignored, this is returned |
No return? | this is returned |
Arrow function? | โ Not a constructor |
๐น 7. Apply It in a Fun Way
๐งช Mini Project: TodoApp
Constructor
1. Create a constructor `TodoApp(title)`
2. Add `addTodo()` and `listTodos()` methods
3. Store todos in an array
4. Display summary with total count
Bonus: Extend it!
Add a
deleteTodo(id)
Save to
localStorage
Add a simple UI (bonus project)
โ Bonus Insights
๐งช Open-source Use
express.Router()
โ constructor behind the scenesnew Vue()
in Vue 2new Error()
in almost every JS lib
โ Common Mistakes
Using arrow functions as constructors
Not using
new
Attaching heavy logic inside constructor body
๐ ๏ธ Performance Tips
Always attach shared methods to
.prototype
Avoid returning objects unless you need to
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
