Quick Tip: Private Variables in JavaScript
Because of JavaScript’s dependence upon globals, it might be easy to forget that creating private variables can be accomplished quite simply, thanks to closures. In just a few minutes, I’ll demonstrate two common techniques which allow for private variables and methods in your projects.
The key to this particular method is to create a variable that is equal to the returned value of a function. That way, we can specifically choose with values and methods are available to our object. Thanks to closures, we’ll still have access to these private variables, even after the object has been returned from our singleton.
var MyObj = function() {
// Private variables
var priv1 = 'private 1',
priv2 = 'private 2';
// Only the methods and properties within this object will be available.
return {
doSomething : function() {
// alert(priv1); // private 1
alert(this.someProp); // someValue
},
someProp : 'someValue'
}
}(); // execute the function when the MyObj variable is initialized.
MyObj.doSomething();
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.

How very interesting :)
pertamax!!
nice tip :D
failed :(
lol
Great quick tip
Great quick screencast, loving these. Can you perhaps give a “real-world” example of where and/or how this would be used?
Thanks!
You could place your entire JS project into one of these objects. That way, you only create a single global variable, rather than dozens.
I’m using this in my AIR applications. I got one container object, which represent application and whitinh it a couple of public functions to manipulate private properties. This give ability use OOP in JS like in PHP.
One need to realize, that OOP in JS is not based on Classes, but on Objects (or Prototypes).
@Jeff: On one of my project, I’ve use it to create a modular framework. I used it to avoid variable name conflict, encapsulating variable access and creating a module base framework.
Last thing to remember when working with private var, be carefull by using … Making it private will prevent you from debugging it with firebug.
Do frameworks like jquery make their variables private?
Yes they use encapsulation via an anonymous function and then use a fairly common practice for private variables which is to name them with an underscore in front. These aren’t true private variables of course but aren’t overwritten as often by mistake due to a duplicate variable name.
var _privateVar = “This is a psuedo private variable.”;
coming from a java background, it sucks that we have to go through this round about way of achieving private variables in js but at least its there…hmmm js is a very unique, frustrating and lovable language
Very helpful quick tip.
Finally understand what a self envoking function is and what triggers it.
When you said “execute it” at the very start, I had one of those lightbulb moments.
Many thanks Jeffrey
The lightbulb moments are the best! :)
You can also wrap the function in parenthesis to help remind yourself that it’s self executing.
So, instead of:
var myObj = function() {}();
You would do:
var myObj = (function() {})();
It might seem like needless extra code, but when you have big projects, it helps to remind you that the function is immediately being called. Otherwise, you’d have to scroll down to the end of the function before you realize that it self executes.
Thats very interesting. But is it really selfexecuting like some ? Then it would be a nice alternative for me.
Is that a firefox extension you’re running the scripts in? Which one?
Hello Jeffrey,
thank you very much for your quicktips, they are really very useful!
Please, could you have a look at your quicktip about different layouts by resizing window: http://net.tutsplus.com/videos/screencasts/quick-tip-different-layouts-for-different-widths/ and try to answer my question in comment Nr. 54?
Thank you very much.
Looking forward to another quicktip:-)
Thanks for the quick tip.
Thanks Jeffrey.
I do hope you can answer this…
At http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/ Chris Heilmann says about this method:
“The beef I had with that is that you need to repeat the name of the main object when you want to call one public method from another or access public variables.”
But in your example you’ve not had to repeat the name of the main object (MyObj) to refer to the public variable someProp -you just used the this keyword.
I’m so confused!
I wonder what’s so special about private variables in JS. You learn this kind of stuff in the first weeks of a Computer Science education?! In about every language I can imagine global variables are something that is avoided if possible!?! So what makes it so special in JS – only the fact that many people writing it in fact have no idea of clean code???
nuk – private variables in js ARE special… js does not have “block scope”… (block={} btw)…… block scope is so common that we could take for granted that something in the outermost block is public to all the inner blocks… so public/private is easy… no big deal… how could it be different? well in JS there is no block scope… instead there is “function scope” — where nested functions have special knowledge of their parents… and closure makes this happen…. but when taken too literally this is not true… because this is a special variable, and only !special-things benefit from closure… this is why you might see:
var that = this; //that gives this some closure…
otherwise it would probably refer to window or the result of a coin toss or anything… which is uselessness…
be careful in this the js wilderness.
I just found this screencast and found it very useful. How would you utilize this practice with a library like jQuery?
I was looking through the source code for this new customizable javascript library called jPaq ( http://jpaq.org/ ). It seems that Chris West used closures in an interesting way to achieve truly private variables. He did this in his Color object.
More about closures in JavaScript, read this:
http://blog.morrisjohns.com/javascript_closures_for_dummies.html