JavaScript Classes: Static Methods and Static Properties

Updated: March 11, 2023 By: Khue Post a comment

This concise, straightforward article shows you how to define and use static methods and static properties in a JavaScript class. We will study the theory first and then look at a few practical examples.

Overview

Static Methods

A static method is a method that belongs to the class rather than an instance of that class. You can only access a static method through the class name, not through an instantiated object.

We can define a static method using the static keyword:

class MyClass {
  static myStaticMethod() {
    // method code here
  }
}

To call a static method:

MyClass.myStaticMethod();

A common use case for static methods is when we want to create utility functions that don’t depend on any instance properties or methods.

Static Properties

A static property is a property that is associated with a class rather than an instance of the class. This means that you can access the property on the class itself, without needing to create an instance of the class first.

To declare a static property:

class MyClass {
  static myStaticProperty = 'some value';
}

To access a static property:

console.log(MyClass.myStaticProperty);

Static properties are useful when you need to store a value that is related to the class as a whole, rather than to any individual instances of the class.

Words might be boring and confusing. Let’s write some code to get a better understanding.

Examples

These examples are arranged in order from basic to advanced, from simple to complex.

Minimal Example

I think this is the shortest example of static methods and properties in a JavaScript class ever seen.

The code:

class Example {
  static myStaticProperty = 'Hello, world!';
  static myStaticMethod() {
    console.log('This is a static method.');
  }
}

Example.myStaticMethod();
console.log(Example.myStaticProperty);

Output:

This is a static method.
Hello, world!

BankAccount class

This example demonstrates how to use static methods and properties to keep track of and manage a collection of objects. In this case, the objects are bank accounts, and the static methods are used to create new accounts and get the total number of accounts.

The code:

class BankAccount {
  static accounts = [];

  // This static method is used to create a new account
  static createAccount() {
    const account = new BankAccount();
    BankAccount.accounts.push(account);
    return account;
  }

  // This static method returns the total number of accounts
  static getTotalAccounts() {
    return BankAccount.accounts.length;
  }

  balance = 0;

  deposit(amount) {
    this.balance += amount;
  }

  withdraw(amount) {
    if (this.balance < amount) {
      throw new Error('Insufficient balance');
    }
    this.balance -= amount;
  }

  get balance() {
    return this.balance;
  }
}

const slingAcademyAccount = BankAccount.createAccount();
const sampleAccount = BankAccount.createAccount();

slingAcademyAccount.deposit(100);
sampleAccount.deposit(200);

console.log('Total accounts:', BankAccount.getTotalAccounts());
console.log('Sling Academy account balance:"', slingAcademyAccount.balance); 
console.log('Sample account balance:', sampleAccount.balance); 

Output:

Total accounts: 2
Sling Academy account balance:" 100
Sample account balance: 200

Conclusion

You’ve learned how to define and use static methods and static fields. They provide a centralized place to manage and retrieve information related to a group of objects, making code more organized and readable. In addition, since static methods and fields are shared across all instances of a class, they can be more memory efficient than instance methods and fields.

If you find errors or anachronisms in the code examples, please let me know by leaving comments. I will review and update them as soon as possible (if necessary).