the Great JavaScript Closure Pattern explained

Ludovico Fischer

02 Mar 2011

Most of you will have seen it in jQuery, but also maybe in Mustache.js, or even another library:

(function() {
  })();

You know you need this somehow to protect the global namespace etc., But how does it work again? Follow along.

It’s just a function call

Yep, that’s right. You know that in JavaScript you can define anonymous functions:

function()  {

}

Well, you can also call them immediately and that's what the above code does. With that out of the way, let's concentrate on the function body and remember later to see why we would want the function to be executed.

Why you need a function

What does a JavaScript program need like humans need oxygen to breathe? Scope. JavaScript burns scopes faster than a pack of cigarettes in a noir movie, because loops, if/else branches have no scope of their own. The only thing that has a scope is a function and that's why you create functions all the time.

The good thing is that wa can dump pretty much everything in a function body and it will stay there forever in its own parallel dimension. Every object and function defined inside a function body will have access to everything that was in the function body at the moment it was defined. That's the famous closure property. (Hint, hint: and that's why we'll need to execute the function, to get a piece of that parallel dimension into the real, cold, harsh world outside. We need the function to return something or in any case assign something to something).

When you think of it, it's pretty cool. It's like every function was its own little package or module, for languages which have that sort of thing. So just go at it, define whatever variable or and function you want in the closure body.

Moving it outside

Done? But how can I use all of this stuff in my web page?, you will ask. Well, you need to move it outside in a convenient wrapper. The trick is that you only really need to move the interface, the functions that need to be used first hand in the outside world. All the rest can remain forever inside the closure and still be accessible from what you exported.

There are two main techniques being used, but both involve first creating an object to hold your interface.

Building an object for outside

Just do

var MyChampion =  { usefulFunction: function() { // uses things in closure scope};

// other functions }

Inside the braces you can, as already said, access anything that's defined inside the closure. There are a couple of other techniques for building your object, but let's not cover them here. Let's move on to the essential.

Bringing it outside

Finally! As already said, there are two ways to do it. First way: just before the end of your big encircling closure/anonymous function, do

window.whateverNameYouWant = myOutsideMissionary

and your object will be accessible anywhere with all its methods intacts. In this case, you need to execute the anonymous function to perform this assignment.

The other solution is to assign the result of the execution of the anonymous function to a variable outside the closure.

var whateverNameYouWant = (function() {};)();

In that case, the last thing your anonymous function must do is to return the missionary object. So, here you want to execute the anonymous function to actually return that object.

Happy ending

So now our object is out there, making its methods available to the whole world; the global namespace is intact; and you have one thing less to be confused about.

As you explore other JavaScript libraries, you will meet other variations on this pattern. Experimentation is still in full swing in the JavaScript community, but that’s why it’s fun and one day, you too might make the next big invention (but spiky hair is not en vogue anymore).