The power of closures in javascript
Now is the time. I can’t go forward if I don’t talk about closures. What are closures? Closures are your friend. That’s the first thing you need to know about them. They will help you keep your code clean, healthy and easy.
A closures is created every time you create a function in a function (they are also created in other situations too but I won’t talk about them now). When using a closure, you will have access to all the variables defined in the parent function (and all its parent functions too).
Attention! Before reading this article, you should take a look at 3 ways of creating functions in javascript.
Write your first closure
[source:javascript]
function function1() {
var var1 = 1;
// Magic here! I create a function inside another function
function function2() {
var var2 = 2;
// I have access to var1 defined in function1
//(the parent function of the current one)
alert(var1 + var2);
}
// Call function2
function2();
}
// Call function1 (should alert 3)
function1();
[/source]
For the moment, it doesn’t make sense but you will surely find a handy way of using it.
Example of a closure
Example of a closure, I want to alert the ID of the timer (returned by window.setTimeout) after 1 second.
In an old-fashioned (without closures) way, I would do the following.
[source:javascript]
var globalTimer = null;
function createTimer() {
// I create the global timer
globalTimer = window.setTimeout(alertTimerId, 1000);
}
function alertTimerId() {
// Alert the global timer ID
alert(”The timer ID is ” + globalTimer);
}
createTimer();
[/source]
There are many problems with that code. The most obvious one is : it uses a global variable. You never know what happens to global variables between the time it is instantiated and the time it is used. It’s bad.
In a new-fashioned (with closures) way, you would do this.
[source:javascript]
function createTimer() {
// I create an inner-function that alerts the timer ID
function alertTimerId() {
// I call the “timer” variable from the parent function (using closures)
alert(”The timer ID is ” + innerTimer);
}
// I create the timer
var innerTimer = window.setTimeout(alertTimerId, 1000);
}
createTimer();
[/source]
I have solved the global variable problem.
Now, what can I do?
Because closures are not implemented in every programming language (update : though it is not specific to javascript), you’ll have to try it for yourself. I don’t want to give you recipes on how/when to use it, it’s up to you. But I could say that a great ajax web2.0 application normally uses a lot of closures.
Keep in mind that
- Closures are created everytime you create a function in a function
- Closures give you access to variables that are defined in the parent function (and all of its parents)
- A closure keeps a reference to an object, not a copy (more on that later)
- Watch out for memory leaks in Internet Explorer!!!


Muahaha, closures are awesome. You can even take your timeout example a step further and offer a way to remove it. The code would look roughly like:
function createTimer(doSomethingLater, duration) {
// You also don’t need “window” - window just defaults
// to the global namespace. top, parent, content, and
// a few others do this too.
var id = setTimeout(doSomethingLater, duration);
return function removeTimer() {
clearTimeout(id);
}
}
This example is a bit contrived since removing a timeout is easy, but you can see how the logic behind the function is hidden, so you can just call the function instead of capturing the id and calling clearTimeout yourself.
The removal-example becomes alot more relevant when you’re dealing with stuff that’s complicated to remove since you abstract the removal, and if you don’t have any need to remove it, just ignore the return value, and it will be happily gc’d.
You can usually tell when you should be using closures if you’re finding yourself having a object pool somewhere to keep track of data you’d need to do something. When you do find this, closures may very well be your cleaner solution.
Another nifty thing that you showed, but didnt mention, is that variables are scoped by function, instead of the usual way of by code block. That is to say this code is valid:
function foo() {
var arr = [1,2,3];
console.log(i);
for(var i = 0; i
hmmmm, rather introductory article. It doesn’t really lend itself to why you’d want to use closures or some of the other applications they’re quite handy for.
I really don’t want to say to developers WHEN they should use it. They’ll have to find on their own. I prefer it that way
But still, I take your suggestion and will think about a good way to say it.
> Because closures are “specific†to javascript, you’ll have to try it for yourself.
This statement is incorrect. Many languages have support for closures. Many have had it before javascript was created.
Chris, I know that many languages support closures (that’s why I wrote “specific” with quote). But most developers never used them. I heard that even Java has closures…
Dan was speaking about memory leaking when using closures. Here is a great article about that (except for the anti-MS statements but what can we do, there will always be people spitting on MS :P)
http://www.bazon.net/mishoo/articles.epl?art_id=824
Also, a way of creating inner functions that won’t keep reference to the inner values is to use the Function constructor instead of the function keyword. Again, it is up to developers to choose when to use which.
Example:
function foo(e){
var i=0
return new Function(”alert(” + i + ” ” + e + “)”);
}