Andrew Lam
Andrew Lam

Reputation: 3804

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.

Upvotes: 47

Views: 45569

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 121998

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);
}

Upvotes: 69

Pramod Kumar
Pramod Kumar

Reputation: 135

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()
}

Upvotes: 12

Related Questions