Question

Is constructor mandatory in a JavaScript class?

I am reading about JavaScript class from the Mozilla documentation section of 'Class body and method definitions'. Under the Constructor section, it states that

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the super keyword to call the constructor of the super class.

From the statement above, I can confirm that we can't have more than one constructor. But it does not mention whether a constructor is mandatory in a class declaration/expression in JavaScript.

 46  43544  46
1 Jan 1970

Solution

 67

You should just write a class without a constructor and see if it works :)

From the same docs

As stated, if you do not specify a constructor method a default constructor is used. For base classes the default constructor is:

constructor() {}

For derived classes, the default constructor is:

constructor(...args) {
  super(...args);
}
2018-02-07

Solution

 11

No, It is not necessary. By default constructor is defined as :

constructor() {}

For inheritance we use this constructor to call super class as :

constructor() {
    super.call()
}
2018-09-26