JavaScript static method is a method that belongs to the class itself rather than an instance of the class. This means that you can call a static method directly on the class without creating an object of that class.
To define a static method in JavaScript, you use the `static` keyword before the method name. Here's an example:
class MathUtils {
static add(x, y) {
return x + y;
}
static subtract(x, y) {
return x - y;
}
}
console.log(MathUtils.add(5, 3)); // Output: 8
console.log(MathUtils.subtract(5, 3)); // Output: 2
In the example above, we define a `MathUtils` class with two static methods: `add` and `subtract`. We can call these methods directly on the class itself, without creating an instance of the `MathUtils` class.
Static methods are commonly used for utility functions or helper methods that don't depend on any specific instance of the class. They can also be used to create factory methods that return instances of the class.