CodeBlanks Logo Icon CodeBlanks

constructor and instance

JavaScript course · Advanced · Lesson 8/100

Learn to create a new instance with constructor and the new operator.

What is a constructor?

A constructor is a special method that runs when a new instance is created from a class. Its name is always constructor, and it usually sets the initial properties of the instance.

class User {
  constructor(name) {
    this.name = name;
  }
}

Here this points to the new instance, and this.name adds a property to it.

The new operator

To create an instance you use the new operator: const u = new User("Alex");. This expression does the following:

  • Creates a new empty object.
  • Calls the constructor and binds this to that object.
  • Returns the created object.

The result, assigned to u, is an instance of the class.

Exercise Product class

Declare a Product class. Its constructor takes name and price parameters and assigns them to this.name and this.price.

Show example solution
Inside the constructor write this.name = name and this.price = price.
Example solution:
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

Test yourself

  1. What does `new User("Alex")` return?

    new User("Alex")
    • a class
    • a method
    • a property
    • an instance
    Show answer

    an instance — Correct! The new operator returns a new instance of the class.

  2. Create a new instance

    const u = ____;
    Show answer
    const u = new User();
  3. Match the concepts

    constructor
    initializer method
    new
    instance creation operator
    this
    points to the new instance
    instance
    object made from a class

All lessons in Advanced