learn2kode.in

What Is a Constructor in JavaScript?

A JavaScript constructor is a special function used to create and initialize objects. Constructors allow you to define object properties and methods once and reuse them for multiple objects.
Before ES6 classes, constructor functions were the primary way to implement object-oriented programming in JavaScript.

Why Use Constructor Functions?

Constructor functions help you:
They are commonly used in JavaScript objects, OOP concepts, and legacy codebases.

Creating a Constructor Function

A constructor function looks like a normal function but follows two rules:
function User(name, role) {
  this.name = name;
  this.role = role;
}
Here, this refers to the newly created object.
Creating Objects Using a Constructor
You can create multiple objects from the same constructor.
const user1 = new User("john", "Developer");
const user2 = new User("Alex", "Designer");
Each object has its own values but shares the same structure.
The Role of the new Keyword
The new keyword does four important things:
Without new, the constructor will not work as expected.
Adding Methods to Constructors
You can add methods directly inside the constructor, but it’s not recommended for performance reasons.
Not Recommended:
function User(name) {
  this.name = name;
  this.greet = function () {
    return "Hello " + this.name;
  };
}
Using Prototype with Constructors (Best Practice)
Methods should be added to the prototype so all objects can share them.
User.prototype.greet = function () {
  return "Hello " + this.name;
};
This improves memory efficiency.

Constructors vs ES6 Classes

ES6 classes are syntactic sugar over constructor functions.
If you understand constructors, learning classes becomes much easier.

Common Mistakes with Constructors

Avoiding these mistakes leads to cleaner code.

When Should You Use Constructors?

Use constructor functions when:
For modern projects, ES6 classes are usually preferred.

Final Thoughts

JavaScript constructors are a fundamental concept in object-oriented JavaScript. Understanding how constructor functions work will help you write reusable, scalable, and maintainable code—especially when moving toward ES6 classes and advanced OOP patterns.