How to Create a Class in JavaScript

Updated: February 28, 2023 By: Goodman Post a comment

This short and straightforward article shows you 2 ways to create a class in JavaScript, which allows you to define a blueprint for creating objects that share common properties and methods.

Class Declarations

Class declarations are a way to define a class with a constructor and methods:

class ClassName {
  /* properties & methods */
}

In the following example, we will create a class named Robot with a constructor that initializes the name, model, year, and owner properties. We have also defined a greet() method that prints a greeting to the console:

// declare a class
class Robot {
  constructor(name, model, year, owner) {
    this.name = name;
    this.model = model;
    this.year = year;
    this.owner = owner;
  }

  greet() {
    console.log(`Hi, my name is ${this.name}!`);
  }
}

// instantiate a new object / instance
let myRobot = new Robot('Robo', 'ABC-123', 2023, 'Goodman');
myRobot.greet();

Output:

Hi, my name is Robo!

One interesting thing to note about class declarations is that the name of the class (Robot, in this case) can be used both inside and outside of the class definition. For example, you can refer to the Robot class by name within the class definition itself, like so:

// declare a class
class Robot {
  constructor(name, model, year, owner) {
    this.name = name;
    this.model = model;
    this.year = year;
    this.owner = owner;
  }

  // use the class name instead of "this"
  greet() {
    console.log(`Hi, my name is ${Robot.name}!`);
    console.log(`I was built in ${Robot.year} by ${Robot.owner}.`);
  }
}

// instantiate a new class instance
let myRobot = new Robot('Robo', 'ABC-123', 2023, 'Goodman');
myRobot.greet();

Class Expressions

With a class expression, you define the class as a value that can be assigned to a variable:

let ClassName = class {
  /* properties & methods */
}

Let’s rewrite the example above using a class expression:

// declare a class
let Robot = class {
  constructor(name, model, year, owner) {
    this.name = name;
    this.model = model;
    this.year = year;
    this.owner = owner;
  }

  greet() {
    console.log(`Hi, my name is ${this.name}!`);
  }
};

// instantiate a new object / instance
let myRobot = new Robot('Robo', 'ABC-123', 2023, 'Goodman');
myRobot.greet();

Output:

Hi, my name is Robo!

When using a class expression, the name of the class is optional, and we can refer to the class by the name of the variable that it’s assigned to.