JavaScript Static Methods
Static Methods in JavaScript are methods that belong to a class itself rather than to instances of the class. These methods are typically used for utility functions or operations that do not require any specific instance data.
Key Features of Static Methods:
- Static methods are defined using the static keyword.
- They are called on the class itself, not on objects created from the class.
- Static methods cannot be accessed through an instance of the class.
- They are often used to create helper or utility methods.
Example: Using Static Methods
Example
class Calculator {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
// Calling static methods directly from the class
console.log(Calculator.add(5, 3)); // Output: 8
console.log(Calculator.subtract(10, 4)); // Output: 6
Output
8
6
6
Explanation of Code:
- The add and subtract methods are defined as static methods in the Calculator class.
- These methods are called directly on the Calculator class, not on an instance of the class.
Use Case: Creating Utility Methods
Static methods are often used to create utility functions that do not depend on the instance state. Here's an example:
Utility Method Example
class StringUtils {
static toUpperCase(str) {
return str.toUpperCase();
}
static toLowerCase(str) {
return str.toLowerCase();
}
}
//Using static utility methods
console.log(StringUtils.toUpperCase("hello"));
console.log(StringUtils.toLowerCase("WORLD"));
Output
HELLO
world
world
Points to Remember:
- Static methods cannot access instance properties or methods of the class.
- They are useful for creating functions that are relevant to all instances of a class.
- Static methods are often used in libraries for utility functions.