Curriculum Series

What is a static method in a class?

What is a static method in a class?

What is a static method in a class?

JavaScript

Static Methods in a Class

We can assign methods to a class itself, not to its instances. Such methods are called static.

In a class declaration, they are prepended by static keyword, like this:

javascript
class User {
static staticMethod() {
alert(this === User);
}
}
User.staticMethod(); // true`

The value of this in User.staticMethod() call is the class constructor User itself (the “object before dot” rule).

Usually, static methods are used to implement functions that belong to the class as a whole, but not to any particular object of it.

You don't need to create an instance of the class to call a static method. You can call it directly on the class.

Here's a simple example:

javascript
class User {
static userCount = 0;
constructor(name) {
this.name = name;
User.userCount++;
}
static createGuest() {
return new User('Guest');
}
static getCount() {
return this.userCount;
}
}
// Using static methods
const guest = User.createGuest();
console.log(guest.name); // "Guest"
console.log(User.getCount()); // 1

These examples demonstrate common use cases for static methods:

  • Creating factory methods (like createGuest)
  • Managing class-level data (like userCount)
  • Creating utility functions (like validation methods)

Static methods are useful when you need functionality that:

  • Belongs to the class itself rather than instances
  • Doesn't need access to instance specific data
  • Provides utility functions related to the class's purpose

Finished reading?

Mark this topic as solved to track your progress.