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.
Note: If you just get started with JavaScript, check out the collection of best free resources to learn JavaScript. 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. Hope this small tip can help you work with static variables in JavaScript and if you have a better approach, please let me know in the comments.
Leave a Reply