JavaScript

This page gently explains JavaScript class syntax as a blueprint for objects that share data and behavior.

What you will learn

class

A class is a template for creating objects with common properties and methods. For example, a Dog class can describe what every dog object stores and does, while each object can have its own name.

A basic class

JavaScript

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

  bark() {
    console.log(this.name + " says woof!");
  }
}

const pochi = new Dog("Pochi");
pochi.bark(); // Pochi says woof!

When is a class useful?

Classes are useful when many objects have the same kinds of data and actions. Do not create a class only because it is available; a small object or a function may be clearer when there is no shared structure.

Related topics