Skip to content

JavaScript static variable in function | Example code

  • by

JavaScript static variable in a function is particular to that function. That is, you can only access the variable in that function.

The static variables maintain their value between function calls and are tidier than using a global variable because they can’t be modified outside of the function.

JavaScript static variable in a function

A simple example code has a function called “foo” and it has a static variable called “counter”. Each time it is called the variable is incremented and written to the console log.

<!DOCTYPE html>
<html>
<body>
  <script>    
    function foo() {

      if( typeof foo.counter == 'undefined' ) {
        foo.counter = 0;
      }
      foo.counter++;
      console.log(foo.counter);
    }
    foo();
    foo();
    foo();

  </script>  

</body>
</html>

Output:

JavaScript static variable in function

Or you can create a static variable in a function by using a closure. A closure is a function that has access to variables from its outer (enclosing) scope, even after the outer function has finished executing. Here’s an example of how you can create a static variable in a function:

function exampleFunction() {
  // Static variable
  let staticVariable;

  // The actual function that uses the static variable
  function innerFunction() {
    // Check if the static variable is undefined
    if (typeof staticVariable === 'undefined') {
      // If it's undefined, initialize it
      staticVariable = 0;
    }

    // Now you can use and modify the static variable
    staticVariable++;

    console.log(staticVariable);
  }

  // Return the inner function or use it as needed
  return innerFunction;
}

// Create an instance of the function
const myFunction = exampleFunction();

// Call the function multiple times, and it will maintain the state of the static variable
myFunction(); // Output: 1
myFunction(); // Output: 2
myFunction(); // Output: 3

In this example, exampleFunction returns the innerFunction, which has access to the staticVariable defined in the outer scope. The static variable persists across multiple calls to myFunction, allowing you to maintain state between function calls.

Do comment if you have any doubts or suggestions on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *