Monday, 17 February 2025

Static method in JavaScript

Static methods are defined on the class itself, not on instances of the class. They are called directly on the class, not on an instance. Static methods are often used to create utility functions that are related to a class but do not require any data or behavior specific to an instance of the class.

staticMethods.js 

class MathUtil {
  static add(a, b) {
    return a + b;
  }
}

console.log(`Sum of 5 and 10 is ${MathUtil.add(5, 10)}`);

 Output

Sum of 5 and 10 is 15

Static Method (add)

The add method is defined as static using the static keyword. This method takes two parameters, a and b, and returns their sum. Since it's a static method, it belongs to the MathUtil class itself, not to any instances of MathUtil.

 

Calling the Static Method

The add method is called directly on the MathUtil class without creating an instance of the class. The expression MathUtil.add(5, 10) calls the add method with 5 and 10 as arguments, and it returns the sum 15.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment