Closures in JavaScript

A closure, in JavaScript, can simply be described as a retained scope; at least, this is how I think of it. The benefit of a closure is in the fact that it retains the scope (the “scope chain”) of the outer (or “parent”) execution context. This behaviour can be used in a number of different ways and has become a useful remedy for quite a few JavaScript gotchas; one of the most common being the “looping problem”.

The looping problem occurs when you create a function within a loop and expect the current value of a variable to retain itself within that new function even though it changes in the loops context before your new function is called. Here’s en example:

var myElements = [ /* DOM Collection */ ];
 
for (var i = 0; i < 100; ++i) {
    myElements[i].onclick = function() {
        alert( 'You clicked on: ' + i );
    };
}

By the time myElements[0].onclick is triggered the value of i will be 99, meaning that whatever element you click on you’ll always get the message, “You clicked on: 99”.

This problem can be solved by creating a function and calling it on each iteration of the loop, while passing i; calling the function will form a brand new execution context where the value of i is retained and can be used in any way within that context, including within the returned function.

function getHandler(n) {
    return function() {
        alert( 'You clicked on: ' + n );
    };
}
 
for (var i = 0; i < 100; ++i) {
    myElements[i].onclick = getHandler(i);
}

Now it works perfectly! A common shortcut used is to create and call the function at the same time, using what is known as a “self invoking anonymous function”:

for (var i = 0; i < 100; ++i) {
    myElements[i].onclick = (function(n) {
        return function() {
            alert( 'You clicked on: ' + n );
        };
    })(i);
}

This way is more common since it’s more concise and heck, it looks cooler! But, the former technique is probably faster since you’re only creating the getHandler function once; not on every iteration.

Note: You don’t have to use a different identifier (n) when passing i to the function but, generally, it’s good practice not to overwrite variables of an inherited scope.

Another common usage of the closure is Yahoo’s (or Crockfords?) Module Pattern:

var someCoolModule = (function() {
 
    var privateVariable = 12345;
 
    return {
        doSomething: function() {
            alert( privateVariable );
        },
        doSomethingElse: function() {
            // ...
        }
    }
 
})();
 
/* The first set of parentheses (around "function(){}") isn't required but is
    used to make it obvious that the function is immediately invoked, thus
    making it obvious that the expression does not necessarily return that
    function; but instead the return value of that function */

By using the module pattern we can create both private and public variables/methods. Since the returned functions inherit the scope of the parent function they have access to all variables and arguments within that context.

The closure is also useful in a situation where a function uses the same resource on every call yet also creates that resource on every call, thus making it inefficient, e.g.

function doSomething() {
    var regex = /[^[](.+?).$/;
    /* Do other stuff ... */
}

Since regex doesn’t change between function calls we can put it elsewhere; and what better place to hide it than in an unexposed private scope:

var doSomething = (function(){
    var regex = /[^[](.+?).$/;
    return function() {
        /* Do someting with "regex"... */
    };
})();

Have any other useful applications of the closure? – please share…

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!