Static Methods in JavaScript
📌 What Are Static Methods?
In JavaScript, static methods are functions defined on a class itself — not on instances of the class. You can only call them using the class name, not from an instance object. Static methods are often used for utility or helper functions.
Note
💡 Static methods cannot be called on class instances — only on the class itself.
🧱 Defining Static Methods
Use the static keyword to define a static method inside a class:
Static Method Syntax
class Calculator {
static add(a, b) {
return a + b;
}
}
console.log(Calculator.add(5, 3)); // 8Note
🧠 Notice how we access add() using Calculator.add() — not via an instance like new Calculator().add().
🧪 Example: Utility Class
Static methods are perfect for utility logic that doesn't depend on object state.
Math Helper Using Static Methods
class MathHelper {
static square(x) {
return x * x;
}
static cube(x) {
return x * x * x;
}
}
console.log(MathHelper.square(4)); // 16
console.log(MathHelper.cube(2)); // 8⚠️ Instance vs. Static Methods
| Feature | Static Method | Instance Method |
|---|---|---|
| Called On | Class | Instance |
| Access this | Class itself | Class instance |
| Keyword | static | None |
📛 Attempting to Call from Instance
Wrong Usage
const calc = new Calculator();
calc.add(1, 2); // ❌ TypeError: calc.add is not a functionNote
⚠️ Always remember that static methods are not available to class instances.
🧬 Static Methods in Inheritance
Static methods are inherited by subclasses and can be overridden.
Static Inheritance
class Animal {
static info() {
return "I am an animal.";
}
}
class Dog extends Animal {}
console.log(Dog.info()); // "I am an animal."✅ When to Use Static Methods
- Utility/helper functions not tied to specific object state
- Factory methods that create instances in specific ways
- Encapsulation of functionality at the class level
📚 Further Reading
>>“Think of static methods as tools 🔧 the class provides — not the objects it creates.”