In programming languages like C, C++, static variables are variables that maintain their value between function calls. Unlike these programming languages, Javascript doesn’t support static variables. It doesn’t provide static keywords. But using a small tip, we can implement function static variables in Javascript and use them for our purposes.
The tip is simple, just remember that in Javascript a function is also an object. An object, of course, can have its own methods and properties. So, why don’t we store our function variables as object’s properties? Let’s see an example:
function foo() {
// do something
// call to static variable
alert(foo.staticVar);
}
// initialize value of static variable
foo.staticVar = 'some value';
foo(); // alert 'some value'
The staticVar in this example is defined outside function body, so its value isn’t destroyed when function call finished. If we call function foo(); again, it still alerts ‘some value’.
We can change value of static variables in function body. This is useful when static variable is used for counting. Let’s see an example:
function count() {
alert(count.num);
count.num++;
}
// initialize count number
count.num = 0;
foo(); // alert 0
foo(); // alert 1
As we see, each function call will increase the count number to 1, and store it into count.num. In this case, count.num plays role of static variables as in other programming languages.





Thanks!