Advertisement
Beginner JavaScript, Classes & Class Syntax

How does the constructor method work in a class?

Short answer

constructor() runs automatically when you call new ClassName(...), initializing instance properties. A class can have at most one constructor.

Save JavaScript mock interview
Advertisement
AModel answer
constructor() runs automatically when you call new ClassName(...), initializing instance properties. A class can have at most one constructor.
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}
const p = new Point(3, 4);
Real-world example
Setting up a new object's initial state, like a shopping cart starting with an empty items array.
Likely follow-ups
  • What happens if you don't define a constructor at all?
Related topics