Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptHow to create Static Variables in JavaScript ?

How to create Static Variables in JavaScript ?

In this article, we will learn to create static variables in JavaScript.

  • Static keyword in JavaScript: The static keyword is used to define a static method or property of a class. To call the static method we do not need to create an instance or object of the class.
  • Static variable in JavaScript: We used the static keyword to make a variable static just like the constant variable is defined using the const keyword. It is set at the run time and such type of variable works as a global variable. We can use the static variable anywhere. The value of the static variable can be reassigned, unlike the constant variable.

Why we create a static variable in JavaScript: We create a static variable in JavaScript to prevent replication and fixed configuration, and it is also useful for caches. 

Example 1: In the below example, we will create a static variable and display it on the JavaScript console.

Javascript




<script>
    class Example {
      static staticVariable = 'neveropen';
        
     //static variable defined
      static staticMethod() {
        return 'static method has been called.';
         }
     }
     // static variable called
     console.log(Example.staticVariable);
     // static method called
     console.log(Example.staticMethod());
</script>


Output: 

neveropen
static method has been called.

Example 2: Static variable is called using this keyword.

Javascript




<script>
    class Example {
      static staticVariable = 'neveropen';
     //static variable defined
     static staticMethod() {
       return 'staticVariable : '+this.staticVariable;
        }
    }
    // static method called
    console.log(Example.staticMethod());
</script>


Output:

staticVariable : neveropen

RELATED ARTICLES

Most Popular

Recent Comments