DEV Community

Pranay Rebeyro
Pranay Rebeyro

Posted on

Constructor in JavaScript

Constructor
Imagine you need to create 100 student objects.Writing each object separately would take a lot of time.Instead, we use a Constructor Function.A constructor acts like a blueprint for creating multiple objects.

Constructor Function
A constructor function starts with a capital letter by convention.It called automatically when object is created

function Student(name, age, course) {
    this.name = name;
    this.age = age;
    this.course = course;
}
Enter fullscreen mode Exit fullscreen mode

Creating Objects Using a Constructor
Use the "new" keyword.

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

let student1 = new Student("Pranay", 21, "ECE");
let student2 = new Student("Rahul", 22, "CSE");

console.log(student1);
console.log(student2);
// Output:
Student { name: 'Pranay', age: 21, course: 'ECE' }
Student { name: 'Rahul', age: 22, course: 'CSE' }
Enter fullscreen mode Exit fullscreen mode

Now we can create as many student objects as we want.

Adding Methods to a Constructor
A constructor can also create methods.

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

    this.greet = function () {
        console.log("Hello " + this.name);
    };
}

let student = new Student("Pranay", 21);

student.greet();
// Output: Hello Pranay
Enter fullscreen mode Exit fullscreen mode

Why Use Constructors?
Without a constructor:

let student1 = {
    name: "Pranay",
    age: 21
};

let student2 = {
    name: "Rahul",
    age: 22
};

let student3 = {
    name: "Anu",
    age: 20
};
Enter fullscreen mode Exit fullscreen mode

You keep writing the same code.

With a constructor:

function Student(name, age) {
    this.name = name;
    this.age = age;
}
let student1 = new Student("Pranay", 21);
let student2 = new Student("Rahul", 22);
let student3 = new Student("Anu", 20);
Enter fullscreen mode Exit fullscreen mode

The code becomes shorter and easier to maintain.

Top comments (0)