Closure in JavaScript – with examples

Here at tinyHippos, we use JavaScript extensively. As a matter of fact it is our core development language right now. So I’m often surprised to see how many developers don’t understand how closure works. There are some great resources out there that I recommend every JavaScript developer read / watch and I’ll post them all at the bottom of this article.

I wanted to start this article with the actual definition for closure, so I went where everyone goes: Wikipedia :-) Here’s what they have to say about closure:

“In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be “closed over” its free variables…”

Well then… that statement really confused me, I mean seriously… a closure is said to be “closed over”, brilliant! Let’s try and define closure in plain English and let’s first look at the two major requirement that a language must implement to be able to have closure.

Closure in plain English

A closure is basically a function that has the following couple of properties

  1. You can pass it around like an object (to be called later)
  2. It remembers the values of all the variables that were in scope when the function was created. It is then able to access those variables when it is called even though they may no longer be in scope

I wish I could say that I’m the one that came up with this easy explanation, but the credit goes to Alan Skorkin. Here’s his article on closure with examples in Ruby.

So… if a function is created inside another function, as is often done when we create a callback function (very common in frameworks like jQuery), the function we created will be have access to the variables that were in scope at the time of it’s creation even if that scope no longer exists when it is executed. I think I might have just confused myself with that statement :-) Since this is meant for developers… let’s do the easy thing and actually look at some code examples!

A simple example of JavaScript Closure

Here is a very simple example of closure in action:

    function calledFunction(passedFunction) {
        passedFunction("newValue");
    }

    function clickMe() {
        var value = "originalValue";

        alert(value);

        calledFunction(function(externalValue) {
            value = externalValue;
        });

        alert(value);
    }    

Go ahead, copy and paste this code and run it. You’ll notice that you’ll get two alerts, the first will say “originalValue” and the second “newValue”. This works because we call calledFunction() and pass it another function as an argument. The functions being passed as an argument has access to the value variable and can modify it. Now, we could have called calledFunction() with a setTimeout and the passed function will still have access to the value variable, even though the the calling function is no longer in scope.

This is all great and dandy… and I’ll show you a couple of ways we can use closure to really help us out. But first…

Closure can hurt you!

Ah yes, closure is great. But if you’re not paying close attention, it can hurt you. Sometimes in ways that are hard to pinpoint. Let’s imagine that we want to write some code that will create a few buttons and then assign onclick callback functions. A simple loop should do:

function addButtonsWithHandlersBad(numOfButtons) {
    var i, button;

    for(i = 0; i < numOfButtons; i++) {
        button = document.createElement("button");
        button.innerText = "Button " + i;
        button.onclick = function() {
            alert("You just clicked Button " + i);
        };

        document.body.appendChild(button);
    }
}    

This looks correct, we call the addButtonsWithHandlersBad() specify the number of buttons we want as the argument and if it weren’t for the name of the function, you’d think we got it right :-) Funny thing is, that when you click on one of the buttons, any button for that matter that has been created using this function, you will always alert the value you passed in as numOfButtons. This might seem like weird behaviour, until you realize that’s closure at work. The function we assign to button.onclick has access to i even after addButtonsWithHandlersBad() is no longer in scope (i.e. it has run it’s course), BUT, it isn’t the value it was when that function was created!!! Remember, addButtonsWithHandlersBad() has finished running, and so we now have access to the latest and greatest value of i (i.e. when the loop is done and i == numOfButtons)

Here is the same example, taking closure into account and doing it right:

function addButtonsWithHandlersGood(numOfButtons) {
    var i, button;

    for(i = 0; i < numOfButtons; i++) {
        button = document.createElement("button");
        button.innerText = "Button " + i;
        button.onclick = (function(x) {
            return function(){
                alert("You just clicked Button " + x);
            };
        }(i));

        document.body.appendChild(button);
    }
}   

Notice that this time our onclick function is actually auto invoked and the function actually returns another function. This allows us to pass in the value of i into that function as it was when the function was created. Now we will have the correct value for the button when it is clicked.

Private Members

Another great use of closure is to create private members. Often you will find yourself in need of private variables that are not available to external sources and can only be accessed from inside your function. The same holds true for private methods (or functions, since we are in JavaScript here). This can be easily achieved with closure.

var namespace = {};

(namespace.someClass = function() {
    var _privateProperty = "some value";

    function _privateMethod() {
        //perform some stuff
    }

    return {
        publicProperty: "some value",

        publicMethod: function publicMethod() {
            //perform some stuff
        }
    }
}()); 

Lets take a closer look at what is going on here. The first thing you’ll notice is that namespace.someClass is equal to an auto invoked function that returns an object literal.  So the function runs it’s course and returns an object that is then assigned to namespace.someClass. _privateProperty and _privateMethod() get closured and are now available to someClass, but since their containing function is no longer in scope (i.e. it has ran already) they are not available to anyone else. Presto, private members :-)

Other resources

There are many other things you can do with closure and understanding it thoroughly will help you immensely when working with any language that supports it. We took advantage of closure in our article Modular Programming Patterns With JavaScript. I’ve just scratched the surface in this article, but here are a few more resources that can help you to better understand closure and JavaScript in general:

Articles:

Books:

Videos:

Feel free to leave any other resources you’re aware of in the comments, our readers will appreciate it.

Happy coding!

About these ads

2 Responses

  1. A little late to the table, however, why did you auto invoke the onClick inside addButtonsWithHandlersGood();?

    Thanks for the article also!

  2. This is great article on “closure” and Java Script. I am a developer myself but never really used this closure function as I should have in creating Java Script.
    Regards
    Jacob Mark

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: