JavaScript Static Methods
14 April 2025 | Category: JavaScript
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
Feature | Description |
---|---|
Defined with static | Use the static keyword inside the class |
Called on the class | Not accessible from instances |
Common use cases | Utilities, 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
Feature | Static Method | Instance Method |
---|---|---|
Called on | Class itself (ClassName.method() ) | Object instance (object.method() ) |
Access to this | Refers to the class itself | Refers to the instance |
Purpose | Utility or helper logic | Behavior 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.