Wednesday, September 3, 2025
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

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11854 POSTS0 COMMENTS
Shaida Kate Naidoo
6745 POSTS0 COMMENTS
Ted Musemwa
7022 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS