Quick Tip: Private Variables in JavaScript
videos

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();

View a live demo.

Add Comment

Discussion 25 Comments

  1. dtbaker says:

    How very interesting :)

  2. kaskuser says:

    pertamax!!
    nice tip :D

  3. Jeff says:

    Great quick screencast, loving these. Can you perhaps give a “real-world” example of where and/or how this would be used?

    Thanks!

    • Jeffrey Way says:
      Author

      You could place your entire JS project into one of these objects. That way, you only create a single global variable, rather than dozens.

      • srigi says:

        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).

  4. Nicolas says:

    @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.

  5. Nicolas says:

    Last thing to remember when working with private var, be carefull by using … Making it private will prevent you from debugging it with firebug.

  6. Do frameworks like jquery make their variables private?

    • Leigh Kaszick says:

      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.”;

  7. nykeri says:

    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

  8. insic says:

    Very helpful quick tip.

  9. Alistair says:

    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

    • Jeffrey Way says:
      Author

      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.

  10. Thats very interesting. But is it really selfexecuting like some ? Then it would be a nice alternative for me.

  11. Jeff says:

    Is that a firefox extension you’re running the scripts in? Which one?

  12. Norguad says:

    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:-)

  13. Thanks for the quick tip.

  14. DaveC says:

    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!

  15. nuk says:

    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???

  16. ml340k says:

    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.

  17. David says:

    I just found this screencast and found it very useful. How would you utilize this practice with a library like jQuery?

  18. David Boone says:

    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.

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.