javascript
  1. javascript-static-method

JavaScript Static Method

Static methods are a special type of method in JavaScript that can be called without creating an object instance. They are associated with the class itself, not an instance of the class. Static methods are commonly used for utility functions that do not depend on the specific instance of the class. In this guide, we will learn about the syntax, example, output, explanation, use, important points, and summary of static methods in JavaScript.

Syntax

The syntax for defining a static method in JavaScript is as follows:

class ClassName {
  static methodName() {
    // code to execute
  }
}

The static keyword is used to denote that the method is a static method.

Example

Here is an example of a static method that calculates the sum of two numbers:

class Calculator {
  static sum(a, b) {
    return a + b;
  }
}

console.log(Calculator.sum(2, 3)); // Output: 5

Output

The output of the above example will be:

5

Explanation

In the above example, we have defined a Calculator class with a static method sum that takes two arguments a and b and returns their sum. We called the sum method using the class name (Calculator) and passing in the arguments (2 and 3), which returns their sum (5).

Use

Static methods are commonly used for utility functions that do not depend on the specific instance of the class. For example, a Math class with static methods for common mathematical operations such as sqrt, pow, abs, log, etc. Static methods can also be used for creating factory methods or for creating singleton classes.

Important Points

  • Static methods are associated with the class itself, not an instance of the class.
  • Static methods are defined using the static keyword.
  • Static methods are commonly used for utility functions.
  • Static methods can be called without creating an object instance.
  • Static methods cannot access instance-level properties or methods.

Summary

Static methods are a special type of method in JavaScript that can be called without creating an object instance. They are associated with the class itself and are commonly used for utility functions that do not depend on the specific instance of the class. Static methods are defined using the static keyword and cannot access instance-level properties or methods.

Published on: