JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Static Methods

14 April 2025 | Category:

Static methods are functions defined on a class itself, not on instances of the class. They are often used for utility functions, factory methods, or any behavior that doesn’t rely on an individual instance.


📌 What is a Static Method?

In JavaScript, you define a static method using the static keyword inside a class.

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

🧠 How to Use It

You call a static method on the class itself, not on an object created from the class:

console.log(MathHelper.add(5, 3)); // Output: 8

Trying to call it on an instance will throw an error:

const math = new MathHelper();
console.log(math.add(5, 3)); // ❌ TypeError: math.add is not a function

đŸ§© Real-Life Example

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

  greet() {
    console.log(`Hello, ${this.name}`);
  }

  static createGuestUser() {
    return new User("Guest");
  }
}

const guest = User.createGuestUser();
guest.greet(); // Output: Hello, Guest

Here, createGuestUser() is a static method that acts like a factory to return a default user.


🧠 Key Points

FeatureDescription
Defined with staticUse the static keyword inside the class
Called on the classNot accessible from instances
Common use casesUtilities, helper functions, factory patterns

❗ When to Use Static Methods

  • When the method logic does not need access to instance properties (this).
  • For utility functions or calculations related to the class but not tied to a specific object.
  • To implement the Factory Pattern or reusable helper methods.

🔁 Static vs Instance Method

FeatureStatic MethodInstance Method
Called onClass itself (ClassName.method())Object instance (object.method())
Access to thisRefers to the class itselfRefers to the instance
PurposeUtility or helper logicBehavior specific to an instance

✅ Summary

Static methods in JavaScript are powerful tools for keeping reusable logic out of object instances. They help write cleaner and more organized code, especially when implementing utility functions or static factory methods.