DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

What is a Constructor ?

Introduction

In JavaScript, a constructor is a special function or method used to create and initialize objects. Whenever you want to create multiple objects with similar structure, constructors help you do it easily and efficiently.

Why Do We Need Constructors?

Without constructors, you would have to manually create objects like this:

let student1 = { name: "Silambu", age: 21 };
let student2 = { name: "sanjay", age: 22 };

This becomes repetitive and messy when creating many objects.

Constructors solve this problem by providing a template (blueprint).

Constructor Using Class (Modern Way)

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

let s1 = new Student("Silambu", 21);
console.log(s1);
Enter fullscreen mode Exit fullscreen mode

Output:

{ name: "Silambu", age: 21 }
Enter fullscreen mode Exit fullscreen mode

How It Works Internally

When you write:

let s1 = new Student("Silambu", 21);

JavaScript does the following steps:

  1. Creates an empty object { }
  2. Sets this to point to that object
  3. Calls the constructor function
  4. Assigns values (name, age)
  5. Returns the object

Concepts

constructor()

  • Special method inside a class
  • Runs automatically when object is created

this

  • Refers to the current object
  • Used to assign values

new keyword

  • Creates object
  • Calls constructor

Constructor Function (Old Way)

Before ES6, constructors were written like this:

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

let s1 = new Student("Silambu", 21);
Enter fullscreen mode Exit fullscreen mode

This still works, but modern JS prefers class syntax.

Top comments (0)