What Is a Constructor?
A Constructor is one of the most important parts of a Class in Object-Oriented Programming.
In most cases, a class contains a constructor because it is responsible for performing the object’s initial setup (initialization) when a new object is created.
Common responsibilities include:
- Receiving the initial data needed to create an object.
- Initializing the object’s attributes.
- Running code that should execute once when the object is created.
Creating a Constructor
To define a constructor inside a class, use the constructor keyword followed by parentheses () and a method body.
// Modelclass Car { constructor() { console.log("This is a car model"); }}
// Objectconst car = new Car();What Happens Here?
We created a class named Car and added a constructor to it.
Then we created an object using:
const car = new Car();As soon as the object is created, JavaScript automatically calls the constructor, which prints:
This is a car modelNotice that we never called constructor() ourselves—it is executed automatically.
Why Do We Use Parentheses?
The constructor is written as:
constructor() {}instead of:
constructor {}because a constructor is a special method, and like every method in JavaScript, it uses parentheses () even when it doesn’t receive any arguments.
Key Takeaways
- A Constructor is a special method inside a class.
- It runs automatically whenever a new object is created.
- Constructors are commonly used to initialize objects and receive initial data.
- A constructor is always written as
constructor()because it is a method.