This post explains How to use static variables in a Javascript function. JavaScript doesn’t support static variables. It doesn’t provide static keywords. But using a small tip, we can implement function static variables in JavaScript and use them for our purposes.
The easiest way to explain how to do this is with an example. If you are remember JavaScript a function is also an object. An object, of course, can have its own methods and properties. So, why don’t we store our function variables as object’s properties? Let’s see an example:
Example : 1
Output:
-----------------------
Example : 2
Output:
------------------------
This is all about using static variables in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
Best part about static variables is that maintain their value between function calls and are tidier than using a global variable because they cannot be modified outside of the function.
The easiest way to explain how to do this is with an example. If you are remember JavaScript a function is also an object. An object, of course, can have its own methods and properties. So, why don’t we store our function variables as object’s properties? Let’s see an example:
Example : 1
function staticExample() { // call to static variable console.log(staticExample.staticVar); } // initialize value of static variable staticExample.staticVar = 'Static Example one'; staticExample(); // return 'Static Example one'
Output:
-----------------------
> "Static Example one"
Example : 2
function counter() { console.log(counter.num); counter.num++; } // initialize count number counter.num = 0; counter(); // display 0 counter(); // display 1
Output:
------------------------
> 0 > 1
This is all about using static variables in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
No comments:
Post a Comment