DEV Community

Cover image for Constructor in JavaScript
Annapoorani Kadhiravan
Annapoorani Kadhiravan

Posted on

Constructor in JavaScript

One of the biggest advantages of JavaScript is the ability to create multiple objects with similar properties and behaviors. Writing each object manually becomes repetitive and inefficient.

To solve this problem, JavaScript provides Constructor Functions.


What is a Constructor in JavaScript?

A constructor is a special function used to create and initialize objects.

Think of it as a blueprint or template for creating multiple objects with similar properties.


Definition

A Constructor Function is a function used with the new keyword to create objects.


Why Do We Need Constructors?

Suppose we want to create three students.

Without constructors:

const student1 = {
    name: "John",
    age: 21,
    city: "Chennai"
};

const student2 = {
    name: "David",
    age: 22,
    city: "Madurai"
};

const student3 = {
    name: "Sam",
    age: 20,
    city: "Coimbatore"
};
Enter fullscreen mode Exit fullscreen mode

This approach works, but it involves repeating code.


With Constructor

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

const student1 = new Student("John", 21, "Chennai");

const student2 = new Student("David", 22, "Madurai");

const student3 = new Student("Sam", 20, "Coimbatore");
Enter fullscreen mode Exit fullscreen mode

Much cleaner and reusable.


Real-Life Example

Imagine a cookie cutter.

One mold can produce many cookies.

Cookie Mold
      ↓
Cookie 1
Cookie 2
Cookie 3
Cookie 4
Enter fullscreen mode Exit fullscreen mode

Similarly,

Constructor
      ↓
Object 1
Object 2
Object 3
Enter fullscreen mode Exit fullscreen mode

Syntax of Constructor Function

function Person(name, age) {

    this.name = name;

    this.age = age;

}
Enter fullscreen mode Exit fullscreen mode

Creating objects:

const p1 = new Person("John", 25);

const p2 = new Person("David", 30);
Enter fullscreen mode Exit fullscreen mode

Understanding this

Inside a constructor, this refers to the object being created.

function Employee(name, salary) {

    this.name = name;

    this.salary = salary;

}
Enter fullscreen mode Exit fullscreen mode

Creating object:

const emp1 = new Employee("John", 50000);
Enter fullscreen mode Exit fullscreen mode

Object created:

{
    name: "John",
    salary: 50000
}
Enter fullscreen mode Exit fullscreen mode

Real-Life Example of this

Suppose a teacher says:

"My classroom"

"My" refers to that teacher.

Similarly,

this.name
Enter fullscreen mode Exit fullscreen mode

means

Current object's name
Enter fullscreen mode Exit fullscreen mode

Creating Multiple Objects

function Car(brand, color, price) {

    this.brand = brand;

    this.color = color;

    this.price = price;

}

const car1 = new Car("BMW", "Black", 6000000);

const car2 = new Car("Audi", "White", 7000000);

const car3 = new Car("Benz", "Silver", 8000000);

console.log(car1);
console.log(car2);
console.log(car3);
Enter fullscreen mode Exit fullscreen mode

Output:

{
brand: "BMW",
color: "Black",
price: 6000000
}

{
brand: "Audi",
color: "White",
price: 7000000
}

{
brand: "Benz",
color: "Silver",
price: 8000000
}
Enter fullscreen mode Exit fullscreen mode

How Does the new Keyword Work?

When we write:

const emp = new Employee("John", 50000);
Enter fullscreen mode Exit fullscreen mode

JavaScript performs four steps.


Step 1: Creates an Empty Object

{}
Enter fullscreen mode Exit fullscreen mode

Step 2: this Points to That Object

this = {}
Enter fullscreen mode Exit fullscreen mode

Step 3: Properties Are Added

{
name: "John",
salary: 50000
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Object Is Returned

const emp = {
name: "John",
salary: 50000
};
Enter fullscreen mode Exit fullscreen mode

Visual Representation

new Employee("John",50000)

        ↓

Creates Empty Object

        ↓

this.name = "John"
this.salary = 50000

        ↓

Returns Object

        ↓

{
name:"John",
salary:50000
}
Enter fullscreen mode Exit fullscreen mode

Adding Methods to Constructor

Methods can also be included.

function Student(name, age) {

    this.name = name;

    this.age = age;

    this.greet = function() {

        console.log("Hello " + this.name);

    };

}

const s1 = new Student("John", 21);

s1.greet();
Enter fullscreen mode Exit fullscreen mode

Output

Hello John
Enter fullscreen mode Exit fullscreen mode

Real-Life Example

Car

Properties:

Brand
Color
Price
Enter fullscreen mode Exit fullscreen mode

Actions:

Start()
Stop()
Accelerate()
Enter fullscreen mode Exit fullscreen mode

Actions are methods.


Example with Laptop

function Laptop(brand, ram, processor) {

    this.brand = brand;

    this.ram = ram;

    this.processor = processor;

    this.showDetails = function() {

        console.log(
            this.brand,
            this.ram,
            this.processor
        );

    };

}

const laptop1 =
new Laptop("HP", "16GB", "i7");

laptop1.showDetails();
Enter fullscreen mode Exit fullscreen mode

Output

HP 16GB i7
Enter fullscreen mode Exit fullscreen mode

Constructor Naming Convention

Constructor names usually start with a capital letter.

Example:

function Student() {}
function Employee() {}
function Car() {}
Enter fullscreen mode Exit fullscreen mode

Not recommended:

function student() {}
Enter fullscreen mode Exit fullscreen mode

Capital letters indicate that the function is intended to be used with new.


Constructor with Default Values

function Mobile(
    brand = "Samsung",
    price = 30000
) {

    this.brand = brand;

    this.price = price;

}

const m1 = new Mobile();

console.log(m1);
Enter fullscreen mode Exit fullscreen mode

Output

{
brand: "Samsung",
price: 30000
}
Enter fullscreen mode Exit fullscreen mode

Constructor for Employee

function Employee(id, name, salary) {

    this.id = id;

    this.name = name;

    this.salary = salary;

}

const emp1 =
new Employee(101, "John", 50000);

const emp2 =
new Employee(102, "David", 60000);

console.log(emp1);
console.log(emp2);
Enter fullscreen mode Exit fullscreen mode

Constructor for Product

function Product(name, price) {

    this.name = name;

    this.price = price;

}

const p1 =
new Product("Laptop", 70000);

const p2 =
new Product("Mobile", 40000);
Enter fullscreen mode Exit fullscreen mode

Constructor for Animal

function Animal(name, type) {

    this.name = name;

    this.type = type;

}

const dog =
new Animal("Tommy", "Dog");

console.log(dog);
Enter fullscreen mode Exit fullscreen mode

Output

{
name:"Tommy",
type:"Dog"
}
Enter fullscreen mode Exit fullscreen mode

Built-in Constructors

JavaScript provides several built-in constructors.

String

const name = new String("John");
Enter fullscreen mode Exit fullscreen mode

Number

const age = new Number(25);
Enter fullscreen mode Exit fullscreen mode

Boolean

const status = new Boolean(true);
Enter fullscreen mode Exit fullscreen mode

Array

const numbers = new Array(10,20,30);
Enter fullscreen mode Exit fullscreen mode

Object

const obj = new Object();
Enter fullscreen mode Exit fullscreen mode

Date

const today = new Date();
Enter fullscreen mode Exit fullscreen mode

Constructor Function vs Object Literal

Object Literal

const student = {
    name: "John",
    age: 21
};
Enter fullscreen mode Exit fullscreen mode

Suitable for one object.


Constructor

function Student(name, age) {

    this.name = name;

    this.age = age;

}

const s1 = new Student("John", 21);

const s2 = new Student("David", 22);
Enter fullscreen mode Exit fullscreen mode

Suitable for multiple objects.


Object Literal Constructor Function
Single object Multiple objects
Simple Reusable
Less code for one object Less repetition
No blueprint Blueprint approach

Constructor Function vs Factory Function

Factory Function

function createStudent(name, age) {

    return {
        name,
        age
    };

}

const s1 =
createStudent("John", 21);
Enter fullscreen mode Exit fullscreen mode

Constructor Function

function Student(name, age) {

    this.name = name;

    this.age = age;

}

const s1 =
new Student("John", 21);
Enter fullscreen mode Exit fullscreen mode

Factory Function Constructor Function
Uses return Uses new
No this Uses this
Creates objects Creates objects
Easier to understand Traditional approach

What Happens Without new?

function Student(name) {

    this.name = name;

}

const s1 = Student("John");
Enter fullscreen mode Exit fullscreen mode

Without new, the function behaves like a normal function and may cause unexpected results.

Always write:

const s1 =
new Student("John");
Enter fullscreen mode Exit fullscreen mode

Real-World Analogy

Think about a university.

Blueprint

Student Form
Enter fullscreen mode Exit fullscreen mode

Contains:

  • Name
  • Age
  • Department

Using that form:

Student 1
Student 2
Student 3
Student 4
Enter fullscreen mode Exit fullscreen mode

The form is the constructor.

Each student is an object.


References :

https://www.w3schools.com/js/js_object_constructors.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

Top comments (0)