Don’t worry, closures is not a complex concept to learn if you break it down into small parts as I’m doing here. What I usually do to keep things in my mind for good is to sketch up a mind map. Yep, a mind map like this one above that has the central subject in the middle and several branches off it. Each branch is a small part of the central subject and this drawing you see is similar to how our brain store information, therefore, it’s a great way to study things.

After this small introduction to mind maps, let’s start with this interesting subject: closures.

First of all, what’s a closure?

Sorry, but there’s no simple definition for that. I personally find the definition of closure harder to explain than the to implement it. My attempt to define closure would be:

In simple words, closure is the scope created by a function which encloses variables and other functions creating a separate “environment”.

Look at the code below, this is an example of closure. Yes, a simple function called myClosure() with a local variable a defined in it and a var a declared outside the my function. Note that when we execute that code below, the variable a inside the function is protected from the outside, because myClosure function is enclosing the the local variable.

var a = "outside closure"; function myClosure() { var a = "inside closure"; alert(a); // "inside closure" } myClosure(); alert(a); // "outside closure"

So, this is a closure. Nothing so fancy, right?

Yes, nothing fancy in this example but further on we’ll have some better ones.

Remember the mind map in the beginning of the article? Now we’ll go through each of the branches with a bit of examples and notes.

1. Access To Outter Variables (By Reference, Not Value)

This item says that we can access all outter variables by reference from within our closure. So, let’s demonstrate it by incrementing the previous code including an inner function inside myClosure().

var a = "outside", b = "another outside"; function myClosure() { var a = "inside"; // Inner function function inner() { console.debug(a); console.debug(b); } inner(); } myClosure(); // output: "inside" "another outside" b = "hey"; myClosure(); // output: "inside" "hey"

Note that inner() has access to all outter variables (a and b) by reference, it means if we change the value of b for example, inner() will automatically get the new value.

2. Variables Outlive After Being Returned

That’s a pretty exciting use of closures, check this another example and an interesting use of it. In the code below, when myConcat() is executed it returns a function enclosed in a scope, prefix is also enclosed. With that in mind, sayWelcomeTo and sayByeTo are two closures with different environment from each other.

function myConcat(prefix) { return function(sufix) { return prefix + " " + sufix; } } var sayWelcomeTo = myConcat("Welcome"); var sayByeTo = myConcat("Bye") alert(sayWelcomeTo("Michael")); // Welcome Michael alert(sayByeTo("John")); // Bye John

This example above shows us that closures keep the state of variables when the function was defined.

To make it more clear, look at the screenshot below showing how you can easily see the closure scope and local scope when debugging in Chrome. The closure keeps the value “Welcome” from the time it was created.



3. Emulate Private and Public Methods

This is an emulation because javascript doesn’t have this access modifiers (private, public) like Java does, but with closure we can do something similar. This way of having private and public methods in javascript is also known as “module pattern”.

So let’s say you need a javascript code to make mathematical divisions (Ok, this is just to illustrate). To do that let’s create a module with all necessary methods and make them public or private according to what we need to expose and what we need to hide.

var DivisionModule = (function() { var isDivisorZero = function(divisor) { // private return divisor === 0; }, doDivision = function(a, b) { if(isDivisorZero(b)) { return "Divisor cannot be zero"; } return a/b; }; return { doDivision: doDivision // doDivision() is public } })(); DivisionModule.doDivision(9, 3); // 3

In the example above isDivisorZero() is a private method because it’s not in the return statement. See below how we exposed just the doDivision() method, everything else is private.

What made this possible is this notation below:

// This notation below makes the function be immediately executed and a closure is created. (function() { })();

4. Closure and Loops: Caution here!

Always remember that closures keep the reference of outter variables instead of value. This piece of advice can be particularly important in loops with closures because if you don’t take that into account, something like this can happens.

<a href="#">Green</a> <a href="#">Red</a> <a href="#">Blue</a>

var colors = ['green', 'red', 'blue']; // Doing the wrong way for(var i=0; i<colors.length; i++) { document.getElementsByClassName(colors[i])[0].onclick = function() { alert(colors[i]); // undefined }; }

The code above was meant to show an alert box with the colour that was clicked on. But instead what we get here is an undefined , do you know why? Because the alert() is using the variable i by reference and by the time we click on any link the variable i will have the value 3 for all the links.

See this code live: http://jsfiddle.net/rL4su/

What we can do to fix it is to store the value o i in a separate closure for each link so each link will have its proper value. Below is the correct code:

var colors = ['green', 'red', 'blue'], clickEvent = function(position) { // this closure will have position stored inside return function() { alert("My favorite color is " + colors[position]); }; }; for(var i=0; i<colors.length; i++) { document.getElementsByClassName(colors[i])[0].onclick = clickEvent(i); }

The value of the variable position will be the same when the function was created.

See this code live: http://jsfiddle.net/rJGhg/