JavaScript › Classes & Class Syntax

How does the constructor method work in a class?

Beginner

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.

Common follow-ups: What happens if you don't define a constructor at all?