How to use static variables in a Javascript function
Posted September 29th, 2009 in Javascript
There may be times when a static variable is needed in a Javascript function; static variables maintain their value between function calls and are tidier than using a global variable because they cannot be modified outside of the function.
Example
The easiest way to explain how to do this is with an example. The following example function is called "foo" and it has a static variable called "counter". Each time it is called the variable is incremented and written to the document.
function foo() {
if( typeof foo.counter == 'undefined' ) {
foo.counter = 0;
}
foo.counter++;
document.write(foo.counter+"<br />");
}
When foo() is first called, foo.counter has not yet been defined. The first line in the example function above checks to see if it's not yet defined and if not initialises it with a value.
Calling foo() multiple times like so:
foo(); foo(); foo(); foo();
would write this to the document:
1 2 3 4
Related posts:
- Setting default values for missing parameters in a Javascript function (Tuesday, November 24th 2009)
- Use jQuery's data() method to store data in the DOM (Tuesday, July 7th 2009)
- How to check if a Javascript function exists (Saturday, July 5th 2008)
- Assigning values to associative arrays in Javascript (Sunday, December 30th 2007)
- Testing if a Javascript variable is defined (Tuesday, October 23rd 2007)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
