Class Constructor in javascript

Default values with class constructor How to define constructor? What is a class constructor? Syntax of constructor()

What is a class constructor?

Constructor is a special method of a class which is used for creating and initializing objects. When a class is created, the constructor() is immedietly invoked.

How to define constructor?

It is necessary to keep name of constructor is 'constructor', otherwise, javascript will add an empty constructor method.

A constructor cannot be getter, setter, async or generator.

There can be only one constructor method in a class. If the constructor method is more than one.

It is introduced in javascript in Ecmasript6 feature.

A constructor method must be done before any methods can be called on an instantiated object.

Syntax

constructor(arguments) {

// code

}

In constructor, arguments are optional.

If you don't provide your own constructor, then a default constructor will be enabled by javascript.

Return Value

A cosntructor returns an object. If any other obejct is not specified in return value, it returns default object. It does not return any primitive value.

Example

class Person{

constructor(name){

this.name=name;

}

introduce(){

console.log("Hii, I am ",this.name");

}

};

const myName = new Person("ankit");

myName.introduce();

Default values with class constructor

Like any regular functions, constructor function properties may have a default value too.

For giving default value, we can pass arguments as below in the example.