How to use Static Variables in JavaScript?


The keyword "Static" is used for defining a static method or a static property of a class. The benefit of a static method is that we do not need to create an instance or object of the class. It does not have multiple values. It will have a single static value defined during initialization.

The keyword static is similar to the const keyword. It is set at the run time when the initialization takes place and these types of variables have global presence and scope. We can use these static variables anywhere over the script.

Note − We can reassign and change the value of a static variable, unlike a const variable.

Example 1

In this example, we are creating a Simple HTML page. We have added a script that has an Example Class. The class contains the static value that is initialized during Run-time and therefore used afterward in the code.

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>Static Variables</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script type="text/javascript">
      class Example {
         static staticVariable = 'Welcome To Tutorials Point';
         // Defining the Static Variables
         static staticMethod() {
            return 'I am a static method.';
         }
      }
      // Calling the Static Variables
      console.log(Example.staticVariable);
      console.log(Example.staticMethod());
   </script>
</body>
</html>

Output

It will produce the following output in the Console.

Welcome To Tutorials Point
I am a static method.

Example 2

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>Static Variables</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script type="text/javascript">
      class Example {
         static staticVariable = 'Welcome To Tutorials Point';
         // Defining the Variable under a Static Method
         static staticMethod() {
            return 'staticVariable : '+this.staticVariable;
         }
      }
      // Calling the above static method
      console.log(Example.staticMethod());
   </script>
</body>
</html>

Output

On successful execution of the above program, it will produce the following output in the Console.

staticVariable : Welcome To Tutorials Point

Updated on: 28-Apr-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements