lkubuntu

A listing of random software, tips, tweaks, hacks, and tutorials I made for Ubuntu

Explaining Javascript Closures Simply

Please note that this article might not be entirely accurate, it is simply meant as a very simple explanation that will get you in the right path to understand them. If you wish for a technically correct answer, see this question on Stack Overflow.

Javascript Closures tend to confuse people who aren’t used to Javascript (don’t feel bad if you’re in this category, Javascript is a weird language, I am certainly included in this category as well).

However, they’re really simple. But many guides tend to make them seem more complicated than they really are. Stack Overflow contains a wonderful array of answers that ended up leaving me more confused than when I started.

So, I’ll give the answer that I believe would have made it clearest to me: A closure in Javascript inherits the stack of the function that declared it. The stack is an object, in the sense that it only goes away when there are no more references.

If you understand what that means, then great! Hopefully this helped! If not, I’ll explain :)

First, a closure in javascript is basically a ‘lambda’, a sort of ‘anonymous function’, and if these terms confuse you (don’t feel stupid if they do, I think we all suck with terms), here’s what it looks like:

setTimeout(/* This is a closure! --> */ function() {
    alert("Hello world!");
} /* <-- End of the closure */, 1000);

You’ve probably seen these everywhere in Javascript.

Now, the “stack” (in Javascript) is basically the local variables in a function. For example:

function hello() {
    var first = "Hello";
    var space = " ";
    var second = "world!"

    var message = first + space + second;

    /* first, space, second, and message are all part of the "stack" */
}

Technically, every function in Javascript is a closure, so therefore, every function inherits the stack of the function that declared it, not the stack of the function that calls it.

In other words:

function hello() {
    var message = "Hello world!";

    return function() {
        alert(message);
    };
}

var message = "Farewell planet";

var closure = hello();
closure(); /* This will output "Hello world!", because it inherits hello's stack */

But doesn’t the stack end once hello() has finished running? Nope, the stack is like an object (it might actually be one, I’m not sure), in the sense that the object will live so long as there is a reference to it. The closure has a reference to it (every object has a reference to their stack), and therefore, the stack is still alive.

What if a closure makes a new variable .. will that change be reflected in the stack of the old function? Nope, every function makes a new stack, that inherits the parent stack (the stack of the parent function that declared this function). For example:

function hello() {
    var first = "Hello";
    var second = "world!";

    [
        function() {
            first = "Goodbye";      // Modifies 'first' in the parent stack

            var second = "planet!"; // Notice the "var" .. this makes a new variable
                                    // in the _current_ stack.
                                    //
                                    // Any future reference to 'second' will refer
                                    // to the variable in the _current_ stack, not
                                    // the variable in the parent stack.

            second = "galaxy!";

            var message = "Hi";     // This was declared in the current stack, message
                                    // will not be declared in the parent stack.
        },
        function() {
            console.log(first);     // "Goodbye"
            console.log(second);    // "world!"
            console.log(message);   // message isn't declared
        }
    ].forEach(function(x) {x()});   // Runs these functions, one after the other
}

That’s about it!

I hope this helped you to understand how closures worked in Javascript. If you’re still confused, feel free to leave a comment!

I’m not an expert on this, and certainly, this guide isn’t meant as an expert technical analysis of how closures work, it’s mainly just meant as a (hopefully) simple bird’s-eye view of how  they work. As I mentioned a few times before, you can find a more detailed explanation at Stack Overflow.

Advertisements

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

%d bloggers like this: