class

Defines a class: a template for creating objects that share the same fields and methods.

On this page

Example

#
JavaScript
class Student {
  constructor(name) {
    this.name = name
    this.points = 0
  }

  addPoints(amount) {
    this.points += amount
    return this
  }
}

const emma = new Student('Emma')
emma.addPoints(50).addPoints(30)

console.log(emma)
console.log(emma instanceof Student)
Console
Student { name: 'Emma', points: 80 }
true

Definition and usage

#

The class keyword creates an object template. The constructor method runs on every new and sets the fields of the new instance through this. Methods written in the class body go onto the prototype, so every instance shares the same functions.

A class can inherit from another with extends. In a derived class’s constructor, you have to call super() before the first use of this, and super.method() calls the base class’s version of a method. Fields and methods marked static belong to the class itself, not to an instance.

Fields prefixed with # are private and only reachable from inside the class. Getters and setters (get, set) expose computed values as if they were plain properties. A class body always runs in strict mode, and unlike a function declaration, you can’t use a class before the line where it’s declared.

Syntax

#
Syntax
class Name {
  field = value
  #privateField = value
  static staticField = value

  constructor(param) {
    this.property = param
  }

  method() {}
  get computed() {}
  set computed(value) {}
  static staticMethod() {}
}

class Child extends Name {}

More examples

#
Inheritance with extends and super
JavaScript
class User {
  constructor(name) {
    this.name = name
  }

  describe() {
    return `User ${this.name}`
  }
}

class Mentor extends User {
  constructor(name, course) {
    super(name)
    this.course = course
  }

  describe() {
    return `${super.describe()}, mentor of the ${this.course} course`
  }
}

const mentor = new Mentor('Jack', 'React')
console.log(mentor.describe())
console.log(mentor)
Console
User Jack, mentor of the React course
Mentor { name: 'Jack', course: 'React' }
A private field, a getter, and a static method
JavaScript
class Wallet {
  #coins = 0

  static withBonus(bonus) {
    const wallet = new Wallet()
    wallet.add(bonus)
    return wallet
  }

  add(amount) {
    if (amount <= 0) throw new RangeError('Amount must be positive')
    this.#coins += amount
  }

  get balance() {
    return `${this.#coins} coins`
  }
}

const wallet = Wallet.withBonus(100)
wallet.add(25)

console.log(wallet.balance)
console.log(wallet)
console.log(Object.keys(wallet))
Console
125 coins
Wallet {}
[]

The #coins field isn’t visible from outside, or in Object.keys(). Reading wallet.#coins outside the class is a syntax error.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Don’t forget new. Calling a class like a regular function, e.g. Student("Emma"), throws a TypeError.
  • A method passed as a callback loses this, e.g. in button.addEventListener("click", game.start). Use an arrow () => game.start(), or game.start.bind(game).
  • Not every piece of code needs classes. A plain object literal is enough for simple data, and a regular function for a single operation.

Related entries

#

Spotted a mistake or missing an example? Write to us.