Skip to main content

JavaScript Classes

JavaScript Class Constructor

Written by Published

The constructor runs when an instance is created and sets up its properties.

It is a special method with a fixed name.

A class can have only one.

Example

Example

javascript

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const ada = new Person("Ada", 36);

console.log(ada.name + " is " + ada.age);

The output is Ada is 36.

What the Constructor Does

It runs automatically when new is used.

Its arguments are whatever was passed to new.

Assigning to this creates a property on the instance.

Syntax

Syntax

javascript

constructor(a, b) {
  this.a = a;
  this.b = b;
}

The name must be exactly constructor.

It Is Optional

A class without one still works; JavaScript supplies an empty constructor.

Example

Example

javascript

class Empty {}

const thing = new Empty();

console.log(typeof thing);

The output is object.

Default Parameter Values

Defaults work here exactly as in any other function.

Example

Example

javascript

class Person {
  constructor(name = "unknown") {
    this.name = name;
  }
}

console.log(new Person().name);
console.log(new Person("Ada").name);

The output is unknown then Ada.

Validating the Input

Throwing in the constructor stops a broken object being created at all.

Example

Example

javascript

class Account {
  constructor(balance) {
    if (balance < 0) {
      throw new Error("balance cannot be negative");
    }
    this.balance = balance;
  }
}

let message;
try {
  new Account(-50);
} catch (error) {
  message = error.message;
}

console.log(message);

A failed constructor means there is no half-built object to worry about.

Doing Work in the Constructor

Derived values can be worked out once and stored.

Example

Example

javascript

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
    this.area = width * height;
  }
}

console.log(new Rectangle(4, 5).area);

A getter would recalculate instead; this stores the value once.

Only One Constructor

JavaScript has no overloading, so a second constructor is a syntax error.

Use default values or a static method instead.

Example

Example

javascript

class Point {
  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }
}

console.log(new Point().x + "," + new Point(3, 4).y);

Defaults cover what other languages would do with several constructors.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Class Constructor</title>
</head>
<body>

  <h1>Class Constructor</h1>

  <p id="out"></p>

  <script>
    class Product {
      constructor(name, price, taxRate = 0.2) {
        this.name = name;
        this.price = price;
        this.total = price * (1 + taxRate);
      }
    }

    const book = new Product("Book", 100);

    document.getElementById("out").textContent =
      book.name + " costs " + book.total.toFixed(2);
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try a different tax rate:

Pass 0.05 as a third argument and watch the total change.

Important Points

  • The constructor runs when new is used.
  • It is optional; an empty one is supplied if you leave it out.
  • Assigning to this creates instance properties.
  • Default parameter values work as normal.
  • A class can have only one constructor.

Conclusion

The constructor is where an instance gets everything it needs to exist.

Validating there keeps broken objects from being created at all.

With no overloading, defaults do the job of several constructors.