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

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 *