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:

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

Explanation of Code:

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

Points to Remember: