JavaScript Class Constructor Tutorial

In this section, we will learn what the Class Constructor is and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the JavaScript class in general.

What Is Constructor in JavaScript?

The `constructor` is a method in a class that will be invoked when an object is going to be created from that class via the `new` or `super` keyword.

This method has no-name other than the keyword `constructor`.

Also in classes we can have only one `constructor` method.

How to Declare Constructor in JavaScript? (Constructor Syntax)

class ClassName{
        constructor(){
          
        }
} 

In the body of the constructor method, we can define the properties that we want the objects that will be created from this class to have.

For example, if we want the objects to have two properties named `firstName` and `lastName`, we can set the constructor like this:

class Person{
        constructor (){
          this.lastName; 
          this.firstName;
        }
} 

Here, after creating an object from the `Person` class, both the `firstName` and `lastName` become the properties of that newly created object.

The constructor method can have parameters as well.

For Example:

class Person{
        constructor (firstName, lastName){
          this.firstName = firstName; 
          this.lastName = lastName;
        }
} 

Default Constructor in JavaScript

The use of `constructor` method in a class is optional. That means we can create a class without adding a constructor method. This is because by default the engine will automatically add one behind the scene to the class if we don’t declare one!

Note: the default constructor in a class has no parameter and an empty body.

So if we have a class like this:

class Person{

//Body...

}

The engine will add an empty constructor to the class like:

      class Person{
        constructor (){   
        }
        //Body...
}

Example: creating class constructor in JavaScript

class Person{
  constructor (firstName, lastName){
    this.lastName = firstName; 
    this.firstName = lastName;
  }

}

const prs = new Person("John","Doe");
console.log(prs.firstName, prs.lastName);

Output:

John Doe

Here in the statement:

new Person("John","Doe");

When we invoked the `Person` class, we’re basically invoking the `constructor` method of this class. So the two arguments that we set here will be assigned to the `firstName` and `lastName` parameters of the constructor, respectively.

Also, after invoking the constructor method, the engine will move into the body of the method and run every instruction in there. At the end, the engine will return the newly created object which can be assigned to an identifier just like the way you saw in this example.

Leave a Reply