DEV Community

pooja Singh
pooja Singh

Posted on

Static Methods in javascript

In JavaScript, static methods are methods that are defined on the class itself rather than on instances of the class. They are used for operations that don't depend on an instance's specific data. Static methods are called directly on the class, not on an instance of the class.

Syntax

To define a static method in a class, you use the static keyword:

class MyClass {
  static staticMethod() {
    return "This is a static method";
  }
}

// Call the static method directly on the class
console.log(MyClass.staticMethod()); // Output: "This is a static method"
Enter fullscreen mode Exit fullscreen mode

Key Characteristics of Static Methods

  1. No Instance Required:
    Static methods cannot be called on an instance of the class; they must be called on the class itself.

  2. No Access to Instance Properties:
    Static methods cannot access this in the context of an instance because they do not operate on individual objects. However, they can access other static methods and properties of the class.

  3. Common Use Cases:

    • Utility functions (e.g., Math class methods like Math.random()).
    • Factory methods for creating objects.
    • General helper methods.

Example

class Calculator {
  // Static method
  static add(a, b) {
    return a + b;
  }

  static subtract(a, b) {
    return a - b;
  }
}

// Using static methods
console.log(Calculator.add(5, 3));        // Output: 8
console.log(Calculator.subtract(10, 6)); // Output: 4

// Attempting to call a static method on an instance will throw an error
const calc = new Calculator();
console.log(calc.add(5, 3)); // TypeError: calc.add is not a function
Enter fullscreen mode Exit fullscreen mode

Static Properties

JavaScript also supports static properties (introduced in ES2022). These are similar to static methods but hold values.

class App {
  static appName = "My Application";

  static getAppName() {
    return `App Name: ${this.appName}`;
  }
}

console.log(App.appName);             // Output: "My Application"
console.log(App.getAppName());        // Output: "App Name: My Application"
Enter fullscreen mode Exit fullscreen mode

Static methods and properties make it easy to define reusable logic or constants that are not tied to any specific instance of a class.

Top comments (0)