How to use static variables in a Javascript functionHow 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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus