🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Static Members

A static member is a property or method that belongs to the class itself. It is shared by every instance, and it is reached through the class name.

Count the instances made

The constructor adds 1 to Player.count for each new player. Two players raise the shared count to 2.

class Player {
  static count = 0;

  constructor(name) {
    this.name = name;
    Player.count = Player.count + 1;
  }
}

const first = new Player("Ada");
const second = new Player("Bo");
console.log(Player.count);

A static method is called on the class

double belongs to MathHelper, not to any one object. The call uses the class name.

class MathHelper {
  static double(n) {
    return n * 2;
  }
}

console.log(MathHelper.double(21));

A factory method builds an instance

createGuest is a static method that returns a new Player. The guest starts with the name Guest.

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

  static createGuest() {
    return new Player("Guest");
  }
}

const guest = Player.createGuest();
console.log(guest.name);

An instance cannot see a static property

count lives on the class, not on the instance. Reading it through the instance gives undefined, while the class gives 1.

class Player {
  static count = 0;

  constructor(name) {
    this.name = name;
    Player.count = Player.count + 1;
  }
}

const player = new Player("Ada");
console.log(player.count);
console.log(Player.count);

Example

class Order {
  static total = 0;

  constructor(amount) {
    this.amount = amount;
    Order.total = Order.total + amount;
  }

  static describe() {
    return "Total of all orders: " + Order.total;
  }
}

const first = new Order(30);
const second = new Order(45);
console.log(Order.describe());

Key points

  • Static member: a property or method that belongs to the class, not to an instance
  • A static property is one value that belongs to the class itself.
  • A static method is called through the class name, not through an instance.
  • The constructor can change a static property each time an instance is made.
  • Reading a static property through an instance gives undefined.
  • Factory method: a static method that builds and returns a new instance

In this example, the Order class keeps one shared total in a static property. Each new order adds its amount to that total. The static describe method reads the shared total and returns one line.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

How do you call a static method?