Limiting Variable Scope Using (function(){})();

By  on  

Simply put, a scope limiter is a self-executing function that defines a variables, performs a task, and clears those variables so that their scope is limited to the function itself. Take the following JavaScript code, for example:

/* do task 1:   */
var lynx = $$('a');
var divs = $$('div');
//(do stuff with links and divs)

/* do task 2 */
var lynx = $$('a'); //error:  lynx already defined!
var lis = $$('li');
//(do stuff with links and list items)

Everything above works but the second task can "see" the variables used to complete task one. This is undesirable as those variables from the first task could cause problems with later tasks. The better way to complete the two tasks is to use scope limiters for each:

/* do task 1:   */
(function() {
	var lynx = $$('a');
	var divs = $$('div');
	//(do stuff with links and divs)
})();

/* do task 2 */
(function() {
	var lynx = $$('a');
	var lis = $$('li');
	//(do stuff with links and list items)
})();

Sweet! Now the variables from the first task have scope only within their executed function scope and cannot affect other JavaScript within the "parent" scope.

Clean code FTW! Keep these techniques in mind when you're writing code that will be repurposed!

Recent Features

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

Incredible Demos

  • By
    MooTools Overlay Plugin

    Overlays have become a big part of modern websites; we can probably attribute that to the numerous lightboxes that use them. I've found a ton of overlay code snippets out there but none of them satisfy my taste in code. Many of them are...

  • By
    Table Cell and Position Absolute

    If you follow me on Twitter, you saw me rage about trying to make position: absolute work within a TD element or display: table-cell element.  Chrome?  Check.  Internet Explorer?  Check.  Firefox?  Ugh, FML.  I tinkered in the console...and cussed.  I did some researched...and I...

Discussion

  1. Proper programming technique is to define variables before use, and to use as few (preferably no) global variables as possible. What you have done in the examples are a work-around.

    I love all your other articles though!

  2. In this case you could define $$('a') globally but my example was more trying to display the two closures working separately.

  3. Will

    Doesn’t this sort of miss the point of closures? I always thought that ‘closure’ meant it ‘closed’ over variables available to it when being declared, so those variables were available even when they went out of scope. It’s hard to explain, but this example might help:

      function makeClosure() {
        var t = "foo";
        return function() {
          alert(t + "bar");
        }
      }
    

    So, you’d call makeClosure, which would return a function. Whenever the returned function was called, the value of t (“foo”) would still be available to it (thus returning “foobar”) even though t’s scope had expired when makeClosure ended.

  4. TheBigBabou

    Sorry David, I don’t want to be offensive, but your code examples are no closures. What you are showing and describing is limiting variables to function scope.

    A closure is a function or codepointer which accesses variables outside its scope. Like here:

    (function () {
    
    var out = 1;
    
    window.setTimeout(function () {
      alert(out);
    }, 100);
    
    })()
    

    The closure here would be the function, which is the first parameter to setTimeout. It doesn’t declare a variable “out”, but is able to access “out” from its outer function scope. As long as a variable stores a reference to this function, “out” is not freed from memory as well.

  5. Ugh, updated my post as the terminology was off. This should make more sense and be more direct.

  6. Good post. Function scoping is a great way to keep your code clean. I often use a model like this:

    (function() {
        // all my private stuff (vars and funcs) go here
        var foo = 'I am scoped, no one else sees me';
    
        var apiMethods = {
            // publicly exposed methods here
            // these methods still have access to privately scoped members
            bar : function() { alert(foo); }
        };
    
        // expose api methods
        window.MyNameSpace = apiMethods;
    })();
    
    // alerts value of foo
    MyNameSpace.bar();
  7. hi David!

    i hope you can help me.
    is it possible to implement your “load more posts” widget (http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/) on a blogger blog? i guess the problem is the php implementation..
    i like very much the script but i supose is not possible to implement it on a blogger thing…

    any idea on that, David? maybe a go around trick…
    thank you very much in advance
    antónio torres
    http://www.vaiumagasosa.com

  8. Devi

    Thanks David! Cleared up some stuff I never really understood in Javascript. This is a good page I came across on function scope in Javascript as well:

    http://www.programmerinterview.com/index.php/javascript/javascript-function-scope/

  9. hiho

    Hi, ty, this is recommended to do today? or the pattern changed?
    PD: sorry for my english :p

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!