Tip Details

Rate as: Positive Negative

Static variables in Javascript

Static variables are variables, typically used in functions, that maintain their value between function calls. Javascript does not support static variables per se; their is no static keyword in the language. However in javascript all functions are also objects and we can use this fact to simulate static variables. All we have to do is create a variable that is a member of the function, and since it's now part of an object, the value will be retained between calls. While there aren't truly static in the strictest sense of the word, they maintain their value between functions calls, and that usually serves the purpose.

As an example, consider a completely lame, but very instructive, function that keeps track of the number of times that it has been called. Here's how it might look:

function countMyself() {
    // Check to see if the counter has been initialized
    if ( typeof countMyself.counter == 'undefined' ) {
        // It has not... perform the initilization
        countMyself.counter = 0;
    }

    // Do something stupid to indicate the value
    alert(++countMyself.counter);
}

Each time that the countMyself function gets called from the page, the value is shown increasing by one. Using this trick, you can easily simulate static variables in Javascript.
Rating: 90% positive, 99 total Votes
Categories: javascript web programming
Added: on Aug 03, 2007 at 4:19 pm
Added By: an anonymous user
Searches: javascript static variable function web

Comments on this Tip

Add a Comment
nice one!
– Added by an anonymous user on Aug 04, 2007 at 6:21 am
works great
– Added by an anonymous user on May 08, 2008 at 4:19 pm
Just what I needed, thanks!
– Added by an anonymous user on Aug 15, 2008 at 10:42 am
Thanks!
– Added by an anonymous user on Sep 12, 2008 at 12:18 pm
Excellent, I found other examples but this is by far the neatest and easiest to follow/modify.
– Added by an anonymous user on Oct 30, 2008 at 6:27 am
Very nice indeed. I'm going to use it every time I need some kind of af slide-show on a web page.
– Added by an anonymous user on Nov 23, 2008 at 4:56 am
Full of Need
– Added by an anonymous user on Nov 26, 2008 at 1:48 am
I used a slightly different but equivalent version of this:
if(this.ascending === undefined)
this.ascending = false;
in one of my own scripts (there is separate code later so ascending flips every time the function is called). The only problem is it adds overhead to every function call, which is why I'm seeking a better way.
– Added by an anonymous user on Dec 27, 2008 at 5:29 am
var id1 = function(){var n = 0; return function(){return n++;};}();
with({n:0})var id2 = function(){return n++;};
alert(id1());alert(id1());alert(id1()); //0; 1; 2;
alert(id2());alert(id2());alert(id2()); //0; 1; 2;
_es
– Added by an anonymous user on Jan 25, 2009 at 10:44 am
There's no magic here. countMyself.counter is a global variable and global variables live as long as the application.
– Added by an anonymous user on Mar 02, 2009 at 7:39 pm
Works great and very good idea. It saved me a lot of time. Thanks
– Added by an anonymous user on Mar 05, 2009 at 6:43 am
countMyself.counter is not a global variable. Attempt to output countMyself.counter outside of the script - it shows up as undefined
– Added by an anonymous user on Apr 14, 2009 at 11:30 am
Actually - you're right - it is a global variable (I misspelled it during testing)
– Added by an anonymous user on Apr 14, 2009 at 11:32 am
To make it a local variable use this.counter instead. That makes it a local variable, unaccessible with countMyself.counter or this.counter (outside of the script).
– Added by an anonymous user on Apr 14, 2009 at 11:35 am
What is so great about this as opposed to:

var counter = 0;

function get_count() {
alert( ++counter );
}
– Added by an anonymous user on May 29, 2009 at 7:24 am
very nice and useful tip. I was looking for static variables in javascript for long time. thanx alot
– Added by an anonymous user on Jun 01, 2009 at 9:33 am
voila, this is nice... working... good.
– Added by an anonymous user on Jul 16, 2009 at 5:27 am
this comment if for the comment which appears two comments above stating "What is so great about this as opposed to: ".
if you have a global variable then you have to decleare for each function ... say if you have 10 functions then you go declare 10 variable as global... that wont be nice... so static means a lot with respect the "this context"...
– Added by an anonymous user on Jul 16, 2009 at 5:30 am
Great work! Thanks for this!
– Added by an anonymous user on Aug 21, 2009 at 5:17 am
Very sweet! thanks for sharing.
– Added by an anonymous user on Sep 09, 2009 at 8:13 am
thank you. simple and effective knowledge sharing. once again i thank you..
– Added by an anonymous user on Sep 22, 2009 at 1:29 am
what is wrong with all of you!?!?!?! STATIC variable.. STATIC!!! NOT CHANGING! i'm going to flip out on the next person that tries to talk about static variables to me now, lol. if you define a static variable in c++, and then try to modify it - you will be REFUSED!!! you CAN NOT modify static variables. get your terms right please... seriously..
– Added by an anonymous user on Oct 07, 2009 at 11:21 am
lol.. i got my terms wrong x.x; good thing this is anonymous xD was thinking constant.. my apologies
– Added by an anonymous user on Oct 07, 2009 at 11:28 am
Yep, statics retain their value between calls. They are not immutable.
– Added by an anonymous user on Oct 07, 2009 at 7:19 pm
its really a nice example..
– Added by an anonymous user on Oct 09, 2009 at 11:49 pm
Something simpler than the if(){} block:

countMyself.counter = countMyself.counter || 0;

Works practically the same way.
– Added by an anonymous user on Oct 20, 2009 at 2:41 pm
Nice job!This is what i am looking for....
– Added by an anonymous user on Oct 26, 2009 at 3:00 am
Javascript actually does have a "static" reserved word -- it just does not do anything in any current version of javascript.
– Added by an anonymous user on Nov 12, 2009 at 12:21 pm
Great Thank u vary much!!!
– Added by an anonymous user on Dec 12, 2009 at 4:30 pm
Uh, correct me if I am wrong, as I don't consider myself to be a Javascript guru or anything, but I don't think this has anything to do with objects. Actually, this is just the intended nature of how javascript works. What's special about your code isn't that it refers to a property of an object, but that when you made that object you didn't write "var". When you write

var something

... you are making the variable local to that function. When you omit the "var" you are making the variable global (like $GLOBALS in PHP).

In other words, you don't need to use an object to do this; you could very well just use a variable like:

if ( typeof(counter) == 'undefined' ) {
counter = 0;
}
alert(++counter);

It's all about how you declare variables - with "var" is always local, and without it, they are global.

Or, correct me if I am wrong any Javascript gurus...
– Added by an anonymous user on Jan 08, 2010 at 6:48 am
Your Comment:
(how to format)
Rate This Tip:

Verify Humanity:
Sorry, we know it's annoying, but please enter the characters shown in the image to the left so that we know you're an actual person and not an evil spammer. Thanks.
       

Related Tips

Scrolling HTML elements using the keyboard

80% positive, 1 comment - last added on Jul 18, 2008 at 3:53 pm
– Tip added by rlansky on Jun 22, 2007 at 9:34 am

Detecting if a variable exists in Javascript

100% positive, 2 comments - last added on Oct 21, 2009 at 2:29 pm
– Tip added by an anonymous user on Jul 22, 2008 at 8:31 am

Telling when an iframe is done loading

75% positive, 3 comments - last added on May 16, 2009 at 7:48 am
– Tip added by an anonymous user on Apr 18, 2008 at 8:05 am

Length of associative arrays in Javascript

100% positive, 0 comments
– Tip added by an anonymous user on Nov 04, 2008 at 10:13 am

Efficient building of large strings in Javascript

100% positive, 0 comments
– Tip added by an anonymous user on Aug 08, 2007 at 12:52 pm

reading select element values in javascript in IE7

100% positive, 0 comments
– Tip added by an anonymous user on Jul 17, 2009 at 1:28 pm

Optional parameters in javascript functions

100% positive, 0 comments
– Tip added by an anonymous user on Jul 30, 2008 at 10:44 am

Javascript variable naming

100% positive, 1 comment - last added on Jul 22, 2008 at 8:33 am
– Tip added by an anonymous user on Sep 30, 2007 at 7:28 am

Code for creating Javascript CSS charts

100% positive, 0 comments
– Tip added by an anonymous user on Aug 21, 2007 at 12:23 pm

Checking for undefined variables in Javascript

100% positive, 1 comment - last added on Jul 14, 2009 at 5:13 pm
– Tip added by an anonymous user on Jan 14, 2009 at 9:47 am

compressing javascript

100% positive, 0 comments
– Tip added by an anonymous user on Jun 12, 2008 at 3:02 pm

Creating vector graphics in javascript

100% positive, 0 comments
– Tip added by Marcos84 on May 10, 2007 at 2:44 pm

attaching events to nodes in Javascript

no ratings, 0 comments
– Tip added by an anonymous user on Aug 18, 2008 at 11:23 am

animating elements with jQuery

0% positive, 0 comments
– Tip added by an anonymous user on Aug 04, 2008 at 1:46 pm

Avoid invalid title names when opening javascript windows

no ratings, 0 comments
– Tip added by an anonymous user on Aug 07, 2007 at 9:36 am

Nice article on javascript techniques

no ratings, 0 comments
– Tip added by rlansky on Apr 24, 2007 at 8:12 am

Internet Explorer not updating div content

100% positive, 0 comments
– Tip added by an anonymous user on Feb 09, 2010 at 7:40 am

Getting pages to render correctly in IE8

Categories: IE8 web css javascript HTML
100% positive, 0 comments
– Tip added by an anonymous user on Jul 23, 2009 at 10:13 pm

Unobfuscate javascript code

no ratings, 0 comments
– Tip added by an anonymous user on Feb 09, 2010 at 12:07 pm

How to impress the judges of 2009 Calling All Innovators Contest

no ratings, 0 comments
– Tip added by alvinmood on Jun 12, 2009 at 6:05 am