Static Methods
What is a Static Method?
Normally, the methods you define in a class belong to the instances (the objects) created from that class.
However, sometimes you want a method to belong to the Class itself, not to the individual objects. This is where static methods come in. You define a static method by placing the static keyword in front of the method name.
Calling Static Methods
Because a static method belongs to the class, you cannot call it on an object. You must call it directly on the Class name.
class MathUtilities {
static add(a, b) {
return a + b;
}
}
// CORRECT: Calling it on the Class itself
console.log(MathUtilities.add(5, 10)); // Outputs: 15
// INCORRECT: Trying to call it on an instance
const myMath = new MathUtilities();
// myMath.add(5, 10); // TypeError: myMath.add is not a function
Real-World Use Case
Static methods are commonly used to create utility or helper functions that don't need any specific instance data.
For example, imagine an Article class. You might have a static method that compares two articles to see which one was published first:
class Article {
constructor(title, date) {
this.title = title;
this.date = date;
}
// Static helper to compare two instances
static compareDates(articleA, articleB) {
return articleA.date - articleB.date;
}
}
const article1 = new Article("JS OOP", new Date(2024, 0, 1));
const article2 = new Article("Himanshu's Guide", new Date(2023, 5, 1));
console.log(Article.compareDates(article1, article2));
💡 Himanshu's Tip:
You actually use built-in static methods in JavaScript all the time! When you write Math.random() or Date.now(), you are calling static methods on the built-in Math and Date classes. You don't have to use new Math() to use them!
Interview Questions
- How do you define a static method in a JavaScript class?
- Can an instance of a class access a static method?
- What is a common use case for a static method?