static variables in javascript

JavaScript Add comments

static variables in javascript

In javascript functions and objects work in the same manner. Functions are also objects.
so a function can have a member variable like in objects.
A member variable will retain its value between function calls.
So this aspect is used for having a static variable in javascript.
Actually there is no option like static variables in javascript. so here the member variable server as a static variable in javascript.

here is one simple script which uses a static variable to maintain a counter

<script>
function addmore()
{
	if(!addmore.counter)addmore.counter = 0;
	addmore.counter++;
	alert(addmore.counter)
}
 
addmore();
addmore();
 
</script>

or here is another version

<script>
function addmore()
{
	if(!this.counter)this.counter = 0;
	this.counter++;
	alert(this.counter)
}
 
addmore();
addmore();
 
</script>

i have used this for multiple file uploads where there will be an addmore button and a variable to maintain the count of number of uploads to display and once this.counter is greater than 10 then i alert a message that uploads cannot be more than 10.

some people had an idea that why done we use like the following instead of using it like a member function

<script>
var counter=0
function addmore()
{
	counter++;
	alert(counter);
}
addmore();
addmore();
 
</script>

my answer is not to mess up the code with too many declarations which uses the word var…
after a long time we would wonder which variable is for which function
and if the variable is with respect to the context of the process then that will a good practice of maintaing standards and more meaningful.

if you would like to suggest an alternate please comment on this because i would like to know more if there is anything beyond my scope on this.

5 Responses to “static variables in javascript”

  1. Aladin6891 Says:

    Nice solution. Well done!!!

  2. Pankaj kalra Says:

    thanks dear,
    i need a counter u gave very simple code for the same.

  3. shaik mahaboob Says:

    finally i got static variable in javascript,clear solution
    thanks dude

  4. kavi87 Says:

    You can use a closure

    var addMore = (function() {
    var counter = 0;
    return function() {
    counter++;
    console.log(counter);
    }
    })();

    for (var i = 0; i < 10; i++) {
    addMore();
    }

  5. kavi87 Says:

    I meant to say “you can *also* use a closure”, your solution is perfect for the need.

Leave a Reply

Entries RSS