How to create Static Variables in JavaScript ?
To create a static variable in JavaScript, you can use a closure or a function scope to encapsulate the variable within a function. This way, the variable maintains its state across multiple invocations of the function.
- 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 do we create a static variable in JavaScript?
In JavaScript, we simulate static variables using closures or other patterns to share state among instances, persist data between calls, or encapsulate information. These “static-like” variables enhance modularity and encapsulation, providing a way to maintain a state without relying on global variables.
Example 1: In the below example, we will create a static variable and display it on the JavaScript console.
Javascript
class Example { static staticVariable = 'w3wiki' ; //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()); |
Output
w3wiki static method has been called.
Example 2: Static variable is called using this keyword.
Javascript
class Example { static staticVariable = 'w3wiki' ; //static variable defined static staticMethod() { return 'staticVariable : ' + this .staticVariable; } } // static method called console.log(Example.staticMethod()); |
Output
staticVariable : w3wiki
Contact Us