Open In App

JavaScript Static Methods

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
12 Likes
Like
Report

Static methods are functions that are defined on a class but are not accessible through instances of the class. Instead, they are called directly on the class itself. These methods are useful for creating utility functions or shared logic that doesn’t depend on individual object instances.

Syntax

class ClassName {
static methodName() {
// method logic
}
}

Output
8
24

In this example, the add and multiply methods can be called directly on the MathUtils class, without creating an instance.

Characteristics of Static Methods

  1. Class-Based: Static methods are invoked on the class itself, not on instances of the class.
  2. No Access to Instance Properties: Static methods do not have access to ‘this’ or instance-specific properties.
  3. Common Use Cases:
    • Utility functions (e.g., mathematical operations, string manipulations).
    • Factory methods for object creation.
    • Shared logic that doesn’t depend on individual objects.

Use case of Static Methods

1. Static Method Math.max()

The getMax() method is a static method that wraps the built-in Math.max() function, demonstrating how static methods can be used to perform operations directly on the class.


Output
9

The getMax() method takes any number of arguments and returns the highest value using the Math.max() function.

2. Static Method Array.isArray()

Static methods like checkArray() allow you to check for specific conditions (e.g., checking if a variable is an array) without needing to instantiate the class.

The checkArray() method uses the Array.isArray() method to determine if the input is an array.

3. Static Method Counter

Static methods can be used to manage class-level state, such as a counter, without creating individual instances.


Output
1
2
1

The Count class has a static property c, which keeps track of the number of times the inc() method is called. The reset() method allows resetting the counter.

4. Static Method Factory Pattern

Static methods can serve as factory methods to create instances of a class, simplifying object creation and initialization.

The createUser() static method is a factory method that returns a new instance of the User class.

5. Static Method Singleton Pattern

Static methods can be used to implement design patterns like the Singleton, where only one instance of the class is allowed.


Output
true

In the DB class, the getInstance() method ensures that only one instance of the class is created. If an instance already exists, it returns the existing one. This is an implementation of the Singleton pattern, ensuring a single point of access to the class.



Similar Reads