JavaScript

Constructor Method in JavaScript

In JavaScript, the Constructor method is invoked when you create an instance of a class. It is also used to initialize objects within a class. However, JavaScript will automatically create and execute an empty constructor if you have not defined any constructor method for a class.

Constructors in JavaScript can be of different types, such as the Built-in JavaScript Constructors, the Custom Constructor function, and the Constructor method of a user-defined class. Depending upon requirements, you can use these constructors for creating and initializing a class’s object or instance.

This write-up will discuss the Constructors and their types in JavaScript with the help of suitable examples.

Constructor Methods in JavaScript

In JavaScript, there are two types of Constructor Methods:

The below-given section will briefly explain Default and Parameterized ConstructorS and their usage in JavaScript.

Default Constructor Method in JavaScript

A Default Constructor is created automatically by JavaScript if you have not added a constructor method in a particular class. However, if you want to perform any specific operation while creating a class object, you can explicitly define a default constructor method.

Syntax of Default Constructor Method in JavaScript

class ClassName{
  constructor(){
    // body of the default constructor
  }
}

Note: The Constructor Method has no explicit return type.

Example: Default Constructor Method in JavaScript

In the below-given example, we will define a default constructor method for the “Employee” class. According to the definition of the “constructor()” method, whenever an “Employee” class object is created, it will initialize its “name” property to “Alex”, and “age” property as “25”:

class Employee {
  constructor() {
  this.name = 'Alex';
  this.age = 25;
  }
}
const employee1 = new Employee();
console.log("Employee name: " + employee1.name);
console.log("Age: " + employee1.age);

Execution of the given program will create an “employee1” object of the “Employee” class by utilizing the default constructor. The default constructor method will then initialize the specified properties for the “employee1” object. Lastly, the “console.log()” method will print out the values stored in the “employee1.name” and “employee1.age” properties:

Utilizing Default Constructor is helpful when you want to initialize the properties of all of the created objects with the same value. But, what if you need to assign some unique values to the objects while creating them? In JavaScript, you can achieve this functionality with the help of the “Parameterized Constructor” method.

Parameterized Constructor Method in JavaScript

A constructor which comprises parameters is known as the “Parameterized Constructor” method. This type of constructor is mainly used when you want to initialize the properties of the class with some specific values.

Syntax of Parameterized Constructor Method in JavaScript

class ClassName{
  constructor(parameter1, parameter2....., parameterN){
      // body of the parameterized constructor
  }
}

Here, the parameterized constructor accepts parameters passed as “arguments” while creating a class object.

Example: Parameterized Constructor Method in JavaScript

We will create a parameterized constructor method for the “Employee” class that initializes the properties with the values passed as arguments:

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

In the below-given code, “employee1” object of the “Employee” class is created using Parameterized constructor where “Stepheny” is passed as “name” property value, and “25” argument represents the value of “age” property:

const employee1 = new Employee("Stepheny", 25);

console.log("Employee name: " + employee1.name);

console.log("Age: " + employee1.age);

Output

The above-given output signifies that we have successfully created an “employee1” object having the specified property values with the help of the Parameterized Constructor method.

Now, let’s discuss the Built-in Constructors of JavaScript.

Built-in Constructors in JavaScript

The Built-in Constructors are also known as Object Constructors. In JavaScript, when an object of the class “Object” is created, the Object Constructor is called directly, which assists in creating the Object of the specified class.

JavaScript offers built-in constructors for different predefined classes such as “Array”, “Date”, “String”, “Number”, “Boolean”, and “Object”.

The below-given section will demonstrate the usage of some built-in JavaScript Constructors.

Example: Object Built-in Constructor in JavaScript

To create a simple object, you can utilize the “Object” class built-in constructor. For this purpose, you have to pass a “value” as an argument while invoking the Object() constructor:

new Object([value])

In this example, we will create two object named “employeeName” and “employeeAge”, by using the “Object” class constructor:

var employeeName = new Object("Alex");

var employeeAge = new Object(25);

console.log("Employee Name : "+ employeeName)

console.log( "Age : "+ employeeAge);

Output

Remember, you can specify any value in the “Object()” constructor, and it does not change the type of created object. For example, we have initialized “employeeName” with a string value, and “employeeAge” contains a number value. Still, the type of the “employeeName” and “employeeAge” is set to “object”:

Example: Array Built-in Constructor in JavaScript

Similarly, the Built-in constructor of the “Array” class can be used for creating an object that contains array elements:

new Array([value])

By utilizing the Array() class constructor, we will now create an “employees” object that comprises three array elements “Alex”, “Paul”, and “Max”:

var employees = new Array('Alex', 'Paul', 'Max');

console.log(employees);

console.log(typeof employees);

Output

The Constructor method added in a user-defined class have their own significance; however, their scope is restricted, as you cannot utilize these constructors throughout your application whenever the creation of an object is needed. Also, the Built-in Constructor does not permit you to customize itself.

In such a scenario, you can create a Custom Constructor function in JavaScript for customizing the behavior of a Constructor, which can be utilized anywhere in a program.

Custom Constructor function in JavaScript

Custom Constructor function is useful when creating multiple objects with the same properties and methods. These functions are similar to regular functions, except they are invoked with “new” keyword.

Syntax of Custom Constructor function in JavaScript

function FunctionName(parameter1, parameter2....., parameterN)
 {
//body of the custom constructor function
 }

Here, the custom function constructor accepts parameters passed as “arguments” while creating an object.

Example 1: Custom Constructor function in JavaScript

We will define a Custom Constructor function named “Employee” that comprises “name” and “age” properties and one “showInfo()” method. Note that the custom function’s name “Employee” is starting with the Capital letter which distinguish it from the regular functions:

function Employee(name, age) {
this.name = name;
this.age = age;
this.showInfo = function () {
        return "Employee Name: "+ this.name + ", Age : "+ this.age;
  };
}

In the next step, we will define two objects “employee1” and “employee2” using the “Employee” constructor function:

var employee1 = new Employee('Alex', 25);

var employee2 = new Employee('Paul', 35);

Lastly, invoking the “showInfo()” method for the created objects will show the values of the properties passed as arguments:

console.log(employee1.showInfo());

console.log(employee2.showInfo());

Output

We have compiled the essential information related to Constructor methods, Built-in Constructors, and Custom Constructor Functions in JavaScript.

Conclusion

Constructors in JavaScript can be of different types, such as the Built-in JavaScript Constructors, the Custom Constructor function, and the Constructor method of a user-defined class. The Constructor method is further divided into Default and Parameterized Constructors. Depending upon requirements, you can use these constructors for creating and initializing a class’s object or instance. This write-up discussed the Constructors and their types in JavaScript with the help of suitable examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.