JavaScript static variable | Create and Use examples

First, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. But JavaScript doesn’t support static variables or a direct way to create them.

There is no static keywords in JavaScript. But you can implement function static variables in JavaScript and use them for purposes.

JavaScript static variable Example

A function is also an object in JavaScript and an object can have its own methods and properties. You can store function variables as object’s properties.

<!DOCTYPE html>
<html>
<body>
	<script>

		function foo() {
			// call to static variable
			alert(foo.staticVar);
		}
		// initialize value of static variable
		foo.staticVar = 'Static value';

		foo(); 

	</script>
</body>
</html>

Output:

Create JavaScript static variable

Static variable count in Function

You can change the value or increase static variables in the function body. This is useful when the static variable is used for counting.

Let’s see complete HTML example code for it:-

<!DOCTYPE html>
<html>
<body>
	<script>

		function count() {
			console.log(count.num);
			count.num++;
		}

		// initialize count number
		count.num = 0;

		count(); // 0
		count(); // 1
		count(); // 2
		count(); // 3

</script>
</body>
</html>

Output:

JavaScript Static variable count in Function

Do comment if you any doubts and suggestion 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.