Open In App

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.

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.




class Example {
    static staticVariable = 'GeeksforGeeks';
 
    //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

GeeksforGeeks
static method has been called.

Example 2: Static variable is called using this keyword.




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

Output
staticVariable : GeeksforGeeks

Article Tags :