Constructor

Last Updated: 24th October 2025


  • A constructor is a special method used to create and initialize objects in JavaScript.
  • It’s automatically called when you create an object using the new keyword.
  • In ES6 Classes, the constructor is defined using the keyword constructor.
  • It runs automatically whenever a new object is created.
  • Used to set initial values (properties) of an object.

Hinglish Tip 🗣: Constructor ko aise samjho — jab naya object banta hai, ye uska “setup function” hota hai jo initial values assign karta hai.


🧩 Syntax

class ClassName {
  constructor(parameters) {
    // Initialize properties
    this.property = value;
  }
}

Example:

class Student {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  showDetails() {
    console.log(`Name: ${this.name}, Age: ${this.age}`);
  }
}

const s1 = new Student("Amit", 21);
const s2 = new Student("Riya", 22);

s1.showDetails(); // Name: Amit, Age: 21
s2.showDetails(); // Name: Riya, Age: 22

How It Works Internally

  • A new empty object is created:
  • this inside the constructor points to that new object
  • The constructor body runs and adds properties to it
  • Finally, that object is returned automatically

Example Without Class (Old Style)

Before ES6, constructors were just normal functions used with new:

function Car(brand, model) {
  this.brand = brand;
  this.model = model;
}

const c1 = new Car("Tata", "Nexon");
console.log(c1.brand); // Tata
console.log(c1.model); // Nexon

Hinglish Tip 🗣: Pehle class nahi tha — function hi constructor ka kaam karta tha, bas uske saath new lagana padta tha.


💡 Quick Practice

  • Create a Book class with title and author and display details using a method.
  • Add a constructor in Employee class that accepts name and salary and prints both.
  • Try creating a constructor function (old-style) for Product with name and price.
  • Exercise