Static variables in JavaScript
10. November, 2010 Leave a comment
Just to make this clear there is no static variable in the sence of which C#,Java or C/C++ (just to name a few..) offers, but there is a “workaround”. First thing to do is to define a function:
funciton gnabber() {
// Make sure variable is/was initialized
if(typeof gnabber.counter == 'undefined' ) {
gnabber.counter = 0;
}
// Increment and return the "static" variable
gnabber.counter++;
return counter;
}
Now if you call the function i.e.:
gnabber(); // returns 1
gnabber(); // returns 2
gnabber(); // returns 3
The return value will always be one higher. If you want to start the index from 0 you have to put the increment part into an else block:
funciton gnabber() {
// Make sure variable is/was initialized
if(typeof gnabber.counter == 'undefined' ) {
gnabber.counter = 0;
} else {
// If variable already was initialized increment it
gnabber.counter++;
}
return counter;
}
This will result in:
gnabber(); // returns 0
gnabber(); // returns 1
gnabber(); // returns 2
The main thing you are using here is the ability to extend an object in JavaScript, use this where ever you need a static variable with some logic instead of a global variable.