Static Method in JavaScript
In this tutorial, we will learn about static methods in JavaScript classes.
In JavaScript, a static method is a method that is called on the class itself, rather than on an instance of the class. Static methods are often used to create utility functions for an application.
Defining a Static Method
To define a static method in a JavaScript class, you use the static keyword before the method name. Here's an example:
class MathUtils {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
console.log(MathUtils.add(5, 3)); // Output: 8
console.log(MathUtils.subtract(5, 3)); // Output: 2In the above example:
- We define a class
MathUtilswith two static methods:addandsubtract. - We call the static methods directly on the class
MathUtilswithout creating an instance of the class.
When to Use Static Methods
Static methods are useful when you want to define utility functions that are related to the class but do not require an instance of the class to be created. For example, you might use static methods to perform common calculations, validate data, or format data.
Static methods are also useful for creating factory methods that return instances of the class. For example, you might have a static method that creates instances of the class based on certain criteria.
Conclusion
- Static methods in JavaScript classes are methods that are called on the class itself, rather than on an instance of the class.
- Static methods are defined using the
statickeyword before the method name. - Static methods are useful for defining utility functions, factory methods, and other class-related functions that do not require an instance of the class to be created.
- Static methods can be called directly on the class without creating an instance of the class.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on