Static Methods

In JavaScript, static methods are functions defined on a class itself, not on instances of the class. This means you call them directly on the class, rather than on an object created by the class.

Illustration of static_methods
Illustration of static_methods

💡 Key Point

Static methods are used for functionality related to the class but not specific to any instance.

Use the static keyword to declare a static method inside a class.

📌 Deep Dive: Defining and Using a Static Method

JAVASCRIPT
class Calculator {
  static add(a, b) {
    return a + b;
  }
}

// Call static method on the class
console.log(Calculator.add(5, 3)); // Output: 8

// Trying to call on an instance causes an error
const calc = new Calculator();
// console.log(calc.add(5, 3)); // Error: calc.add is not a function
Output
8

Static methods are commonly used for utility functions or operations that don’t depend on instance data.

💡 Usage Tip

Use static methods to group related helper functions inside a class for better organization.

Instance Method vs Static Method
Instance MethodStatic Method
Called on an instance of the classCalled on the class itself
Can access this referring to the instanceNo access to instance properties; this refers to the class
Used for behavior specific to an instanceUsed for utility or helper functions related to the class

Static methods can also be inherited by subclasses:

📌 Deep Dive: Static Method Inheritance

JAVASCRIPT
class Animal {
  static identify() {
    return 'Animal class';
  }
}

class Dog extends Animal {}

console.log(Dog.identify()); // Output: Animal class
Output
Animal class

⚠️ Important

Static methods cannot access instance properties or methods because they are not called on an instance.

Summary:

  • Static methods belong to the class, not instances.
  • Use static keyword to define them.
  • Call them directly on the class, e.g., ClassName.method().
  • They are useful for utility or helper functions related to the class.
  • Static methods are inherited by subclasses.