• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / How to use static variables in a Javascript function

How to use static variables in a Javascript function

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

Check Out These Related posts:

  1. RFC 1321 – MD5 Message-Digest Algorithm
  2. Type casting with PHP
  3. Setting default values for missing parameters in a Javascript function
  4. How to use static variables in a PHP function

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap