The Wayback Machine - http://web.archive.org/web/20080209105120/http://blog.morrisjohns.com:80/javascript_closures_for_dummies
Skip navigation.
Home

JavaScript Closures for Dummies

Closures Are Not Magic

This page explains closures so that a programmer can understand them - using working JavaScript code. It is not for gurus nor functional programmers.

Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!

This article is intended for programmers with some programming experience in a main-stream language, and who can read the following JavaScript function:

function sayHello(name) {
  var text = 'Hello ' + name;
  var sayAlert = function() { alert(text); }
  sayAlert();
}

An Example of a Closure

Two one sentence summaries:

  • a closure is the local variables for a function - kept alive after the function has returned, or
  • a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)

The following code returns a reference to a function:

function sayHello2(name) {
  var text = 'Hello ' + name; // local variable
  var sayAlert = function() { alert(text); }
  return sayAlert;
}

Most JavaScript programmers will understand how a reference to a function is returned to a variable in the above code. If you don't, then you need to before you can learn closures. A C programmer would think of the function as returning a pointer to a function, and that the variables sayAlert and say2 were each a pointer to a function.

There is a critical difference between a C pointer to a function, and a JavaScript reference to a function. In JavaScript, you can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure.

The above code has a closure because the anonymous function function() { alert(text); } is declared inside another function, sayHello2() in this example. In JavaScript, if you use the function keyword inside another function, you are creating a closure.

In C, and most other common languages after a function returns, all the local variables are no longer accessable because the stack-frame is destroyed.

In JavaScript, if you declare a function within another function, then the local variables can remain accessable after returning from the function you called. This is demonstrated above, because we call the function say2(); after we have returned from sayHello2(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello2().

function() { alert(text); }

Click the button above to get JavaScript to print out the code for the anonymous function. You can see that the code refers to the variable text. The anonymous function can reference text which holds the value 'Jane' because the local variables of sayHello2() are kept in a closure.

The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in - similar to how delegates are a method pointer plus a secret reference to an object.

More examples

For some reason closures seem really hard to understand when you read about them, but when you see some examples you can click to how they work (it took me a while).
I recommend working through the examples carefully until you understand how they work. If you start using closures without fully understanding how they work, you would soon create some very wierd bugs!

Example 3

This example shows that the local variables are not copied - they are kept by reference. It is kind of like keeping a stack-frame in memory when the outer function exits!

function say667() {
  // Local variable that ends up within closure
  var num = 666;
  var sayAlert = function() { alert(num); }
  num++;
  return sayAlert;
}


Example 4

All three global functions have a common reference to the same closure because they are all declared within a single call to setupSomeGlobals().

function setupSomeGlobals() {
  // Local variable that ends up within closure
  var num = 666;
  // Store some references to functions as global variables
  gAlertNumber = function() { alert(num); }
  gIncreaseNumber = function() { num++; }
  gSetNumber = function(x) { num = x; }
}

The three functions have shared access to the same closure - the local variables of setupSomeGlobals() when the three functions were defined.

Note that in the above example, if you click setupSomeGlobals() again, then a new closure (stack-frame!) is created. The old gAlertNumber, gIncreaseNumber, gSetNumber variables are overwritten with new functions that have the new closure. (In JavaScript, whenever you declare a function inside another function, the inside function(s) is/are recreated again each time the outside function is called.)

Example 5

This one is a real gotcha for many people, so you need to understand it.
Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.

function buildList(list) {
  var result = [];
  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push( function() {alert(item + ' ' + list[i])} );
  }
  return result;
}

function testList() {
  var fnlist = buildList([1,2,3]);
  // using j only to help prevent confusion - could use i
  for (var j = 0; j < fnlist.length; j++) {
    fnlist[j]();
  }
}

The line result.push( function() {alert(item + ' ' + list[i])} adds a reference to an anonymous function three times to the result array. If you are not so familiar with anonymous functions think of it like:

    pointer = function() {alert(item + ' ' + list[i])};
    result.push(pointer);

Note that when you run the example, "item3 undefined" is alerted three times! This is because just like previous examples, there is only one closure for the local variables for buildList. When the anonymous functions are called on the line fnlist[j](); they all use the same single closure, and they use the current value for i and item within that one closure (where i has a value of 3 because the loop had completed, and item has a value of 'item3').


Example 6

This example shows that the closure contains any local variables that were declared inside the outer function before it exited. Note that the variable alice is actually declared after the anonymous function. The anonymous function is declared first: and when that function is called it can access the alice variable because alice is in the closure.
Also sayAlice()(); just directly calls the function reference returned from sayAlice() - it is exactly the same as what was done previously, but without the temp variable.

function sayAlice() {
  var sayAlert = function() { alert(alice); }
  // Local variable that ends up within closure
  var alice = 'Hello Alice';
  return sayAlert;
}

Tricky: note also that the sayAlert variable is also inside the closure, and could be accessed by any other function that might be declared within sayAlice() or it could be accessed recursively within the inside function.

Example 7

This final example shows that each call creates a separate closure for the local variables. There is not a single closure per function declaration. There is a closure for each call to a function.

function newClosure(someNum, someRef) {
  // Local variables that end up within closure
  var num = someNum;
  var anArray = [1,2,3];
  var ref = someRef;
  return function(x) {
      num += x;
      anArray.push(num);
      alert('num: ' + num +
          '\nanArray ' + anArray.toString() +
          '\nref.someVar ' + ref.someVar);
    }
}

Summary

If everything seems completely unclear then the best thing to do is to play with the examples. Reading an explanation is much harder than understanding examples.
My explanations of closures and stack-frames etc are not technically correct - they are gross simplifications intended to help understanding. Once the basic idea is grokked, you can pick up the details later.


Final points:

  • Whenever you use function inside another function, a closure is used.
  • Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and within eval you can even create new local variables by using eval('var foo =
  • When you use Function() inside a function, it does not create a closure. (The new function cannot reference the local variables of the function calling Function()).
  • A closure in JavaScript is like keeping a copy of the all the local variables, just as they were when a function exited.
  • It is probably best to think that a closure is always created just on entry to a function, and the local variables are added to that closure.
  • A new set of local variables is kept every time a function with a closure is called (Given that the function contains a function declaration inside it, and a reference to that inside function is either returned or an external reference is kept for it in some way).
  • Two functions might look like they have the same source text, but have completely different behaviour because of their 'hidden' closure. I don't think JavaScript code can actually find out if a function reference has a closure or not.
  • If you are trying to do any dynamic source code modifications ( for example: myFunction = Function(myFunction.toString().replace(/Hello/,'Hola')); ), it won't work if myFunction is a closure (Of course, you would never even think of doing source code string substitution at runtime, but...).
  • It is possible to get function declarations within function declarations within functions - and you can get closures at more than one level.
  • I think normally a closure is the term for both the function along with the variables that are captured. Note that I do not use that definition in this article!
  • I suspect that closures in JavaScript differ from those normally found in functional languages.

Links

Thanks

If you have just learnt closures (here or elsewhere!), then I am interested in any feedback from you about any changes you might suggest that could make this article clearer. Send an email to morrisjohns.com (morris_closure @). Please note that I am not a guru on JavaScript - nor on closures.

Thanks for reading.

Nice!

This is one of the best articles I have read on JavaScript.

Usually programmers want to bring their own idioms from languages
they're familiar with, but this article teaches how to program JS with JS.

I have Wrox book about 'professional' JS (Zakas), but it's introduction on closures was pretty superficial.

Very good

Morris,

Thanks, very good examples and explanation

An excellent walkthrough

I am completely self-educated in JavaScript, and while I have been using closures quite successfully in a professional setting for several years, I had very little technical understanding of their nature. This article gave me a much better sense of the possibilities of closures and how to avoid their misuse.

Great article on closures

Thanks - you did a very good job of explaining and demonstrating closures in JavaScript!

Great Article

Great description of closures in JavaScript. Based on how you have described them, I think they are virtually identical to closures in other languages such as scheme and matlab (nested functions).

example 5

In example 5 remark, "i has a value of undefined" is not true. i has the value of 3 and what is undefined is item[i] because the index i is out of range of the array.

re: value of i

Thank you for your correction - I have now updated the article.

Plus I have learnt something! (I had been using old school thinking where loop variables go out of scope.)

re: value of i

Yeah, it's important to remember that with javascript there is only function and global scope.

Simply opening and closing your curly braces doesn't create a new scope (as would happen in C). So the scope of your loop variable 'i' its enclosing function.

Thank you

Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!

I think i know exactly which paper you are talking about! Thank you for this article, you made JS closures very easy to understand!

Looks Good

I've just added a link to my tutorial site so I can check it out later. Looks like a good explaination of closures though.

Thanks,

Drixer - TipClique Tutorials

The Best Tut on Closures

the best course on Closures i have ever seen on internet and on any book. Thank you

when are closure dealloc-ed?

Coming from a C background, I wonder when are those closures dealloced?
In a large loop, can you run out of memory then .

They are garbage collected

One implementation could be that each function that uses one or more closures keeps an internal reference to the closure.

As soon as there are no more references to the function that is using the closure, the function should get garbage collected and also the closures should be garbage collected.

Be aware: you should avoid making DOM element event functions (e.g. onclick) that use closures because it is very very easy to make circular references that IE can't detect. prototype.js, Dojo etc provide helper functions to prevent the leak (they clear all relevant element event functions when the page is unloaded to break circular dependencies - provided that you use their event registration functions :). -- see http://www.codeproject.com/jscript/LeakPatterns.asp for more info.

Can you dump a closure?

Excellent article!

Given you have a closure, does anyone know if there's a way to enumerate the contents of captured stack frame?

Thank you

Thank you for explaining closures so I could understand them - the examples really helped.

ok, but why

Really, very nice article. Certainly more accessible than http://www.jibbering.com/faq/faq_notes/closures.html

You're missing one critcial bit in the beginning of the article: The benefit (assuming there is any) of using closures. At a minimum you really need to include some examples - useful examples - of closures versus non-closure implementation of the same algorithms, or if possible an example - a useful one - of something that cannot be accomplished without closures. The article linked above includes such a section, but to put it mildly the details are not compelling. I want to read something that makes me think "Wow! I can do THAT with closures?!?! Happy days!", rather than what I actually think which is "So what? I can needlessly complicate my js and thereby make it practically unmaintainable by mere mortals? No thanks."

re: ok but why

I think you would need to look at a proper functional language to see good examples of closures in use. Prototype's bind() function or Dojo's dojo.lang.hitch() function use closures.

Apart from a few tricks which can only be done with closures, I try to avoid them in my own code because I think they make code unreadable to many programmers (regardless of the merits of closures).

I only wrote the article because I couldn't read code that used them - I haven't had a functional epiphany yet such that I actually use them regularly. The only place I have really used them is for callbacks:
function(a,b,c) {
  function myCallback() {
    // blah blah blah
    // code that uses a,b,c
  }

  doSomething(myCallback)
}
e.g. when doSomething does an asynchronous XML HTTP call that calls the callback function parameter on completion, or when you don't want doSomething to know about a, b, or c at all. However even then I am cautious.

Thanks for the info

A very good explanation. Thanks. I recently read a book on Ajax and it had a rather complicated and vague explanation of closures. This cleared the air considerably.

Cheers.

Very Helpful

Thank you, the article was very helpful.

I've been using them - but didn't know what they were called

I've been using closures for awhile - but just as a way to create "classes" in JS. By assigning local variables anonymous functions, I was able to use the 'new' keyword for the outer function and use 'dot' notation to access the inner functions.

I wasn't necessarily making the 'return' value of the function a reference to a variable containing a function; but I get the idea.

Thanks for the article!

Solution for Example 5?

Is there a way of correctly implementing what example 5 is trying to do?

(Your captha text is very hard to read, small font and occasionally goes out of bounds)

This is one way...

function buildList(list) {
var result = [];
for (var i = 0; i

It was good.

Hello The examples mentioned here are very useful.

But some examples are not useful they are much confusing so try to sortout and make user friendly examples.

Great Article!

I feel this is a very nice article. Especially examples 6 and 7 about local variables are really nice. Keep up the good work!

Thank you!

Simple and clear! Even though I didn't know almost anything about Javascript!
Thanks!! :)

Thank for the nice explanation

I came across the closures terminology just a few days ago while digging deep into the dojo toolkit scripts and was quite bevildered at the concept. This article has given me a very good foundation to carry forward for going into the depth of the magical world of javascript.
Thanks a ton!!

Closures in Javascript, ... wonderful!

I first heard about closures while learning SCHEME (a Lisp dialect) way back in 1987. And guess what, it was achieved in pretty much the same way: Using lambda expressions to build anonymous functions from
within another function. Thanx for this great tutorial on how to achieve the same with JavaScript.

Good work!

best regards

Manfred

If you are making comments

Notice to commenters :)

  • I delete spam.
  • I do not delete negative comments.
  • I have edited the commenting module of drupal to ask a multiplication question (the captcha was no longer preventing spam.) If it doesn't work blame me!
  • It is difficult to tell some valid comments from spam... Make sure your comment makes sense and is relevant (in whatever language you would like to use). If it has a link and is too short, too dumb, or is non-sensical or a klajsdlfjlj comment, I will probably delete it (I presume such comments are spam links).
  • Please email me if you see any scumbag link spamming comments so I can nuke them (they often copy some text from elsewhere on the page to hide).
  • I dont check this very often, so email me directly if you want a reply.
  • Thanks for reading. I really appreciate the feedback I have received so far and any constructive feedback you might want to give me would be great!
  • Update: links in comments disabled because I was still getting comment spam - boo hoo.

closures and loops

Thanks for the article, Morris!
I was trying to use closures in loop, like:
for(i in array1)
{
array2[i] = function() { return something(array1[i]) }
}

and wondering why it only used array1[array1.length-1].
Now after your explanation everything is pretty clear.
One thing slightly confused me, though: i don't think i'm dummy :)

Borland C++ Builder Closures

Great article. Borland have added a __closure keyword as a (non-standard) extention to C++ in their C++Builder product. Though it can be used for any purpose, it's primary raison d'etre is to provide the ability to assign event handlers to objects in the VCL class library. For example, if a base class defines an OnClick member function that responds to mouse click events, a descendant class can assign its own handler to OnClick as if it were a regular pointer. Without the __closure extension, this would not be possible.

__closure is not a real closure

I have never used C++ builder, but I know Delphi and I would strongly guess that this isn't a real closure, but that instead the keyword defines the equivalent of a C# delegate.

In Delphi you can have two types of function pointers - examples:


type
TFunctionSignature = function(i: Integer): Integer;
TDelegateMethodSignature = function(i: Integer): Integer of object;

TFunctionSignature is mostly equivalent to a normal C function pointer.

TDelegateMethodSignature is a delegate and this type of method pointer is used for wiring events between controls and forms. It is implemented as a struct (size 8 bytes) containing a pointer to a method, plus a pointer to an object (See System.TMethod). When a delegate method is called, self/this is set to the object pointer, and the method/function pointer is then called.

Aside: Pascal also has inner functions that are declared inside a function. These are like closures because the inner function can access and change the variables of the containing function, however everything is on the stack so you can't 'keep' a reference to a function along with it's closure variables.

Thanks

Hi Morris,
Javascript has evolved so much that i can see only now.
I did some javascript work a few years back but then i shifted to enterprise development. After returning from there the world seems so new to me. Thanks for this excellent article
Varun

Excellent

I've been reading an Apress book (Pro JavaScript Techniques) by John Resig and it's great. However, the one concept I really had trouble understanding from his description was that of closures. It was great to stumble upon this page and have it all clear within 5 minutes. Thanks again and keep it up.

Great Explanation!

I just recently really delved into JavaScript and have been doing some pretty cool stuff so I can really appreciate wrapping my mind around something like this! Thanks for an awesome article. Very nice examples! Oh and I realized shortly after starting the article that I had seen closures in the form of a callback scenario like you pointed out above... of course I don't think I or the developer that wrote it at the time knew exactly why the request object was still available. =D

Crystal Clear - great examples

I came over here from http://www.digital-web.com/articles/seven_javascript_techniques/ where I was trying to understand that code. I knew I was missing something - I was looking with C++ eyes and it just didn't make any sense. I had the idea in mind for function pointers, but I was missing the whole stackframe semantic.

This article was exactly what I needed. Thanks.

Great explanation.

I have c and c++ background, but as I first came around with javascript and closures, the concepts behind that language were a bit confusing. I googled a lot and tried to get the "big picture" on javascript to know, how to organize my files and "objects". To really work with javascript, it's absolutely necessary to understand the concepts behind. This article helps a lot.

A problem I had and now think that I understand is the following (Calling a privileged (outer) function from a closure):

function X()
{
var self = this; //Store the actual context in self.

this.prvFunc = function() //Privileged function
{
alert("Hello from prvFunc");
}

var closureFunc = function()
{
//The closure doesn't seem to have "direct" access to
//the outer function. So I used the self variable that
//I set in the constructor.
self.prvFunc();
//Necessary to use self instead of this, because "this"
//seems not valid in this context.
}
}

this is not your grandfather's this

You would need to look for an article about how this works in Javascript. this does not act the same as it does in a traditional OO language such as C++.

Here's the product blurb

If you want to see a brochure website about what I have been working on visit TimeFiler (Just a comment because writing a good article takes time and I am busy!).

Morris

Suggestion

In example 7, you can see an interesting behavior of closures by clicking on the 'closure1' or 'closure2' buttons multiple times.

After you've tried that, hit the
"closure1 = ...
closure2 = ..."
button again, then re-try the lower buttons.

JavaScript *can* detect a closure, well, sort of.

Two functions might look like they have the same source text, but have completely different behaviour because of their 'hidden' closure. I don't think JavaScript code can actually find out if a function reference has a closure or not.

Douglas Crockford's JSLint notifies you of all functions that contain closures.

For example:


function foo()
{
var foobar = 'a string';
var bar = function() { return foobar; }
}

JSLint will correctly report that "foobar" is within a closure.

And although there are some problems with JSLint, that Mr. Crockford did not like me pointing out, it is still an invaluable tool for JavaScript developers.

Thanks - that was a relief

Number 7 saved my... Well let's just say that thanks to your example I was able to do what I wanted which was to create many slightly different tiny closures.

Great explanations.

Using Closures

Closures are extremely valuable in situations where you need to programatically generate code. In JavaScript, there are actually lots of reasons to want to generate code! It's such a flexible language, many Design Patterns can be implemented as auto-generating classes. I recently implemented the Decorator pattern as an "AutoDecorator"- given a class as input, it generates methods at runtime to wrap around that class.

Of course, I didn't know exactly how to use closures to do this until reading this article!

Javascript Closure

Super tutorial. I ran into this term 'closure' today for the first time and the academic explanation I found elsewhere did not actually make much sense. Thanks!

defining and invoking a closure function

In many of the examples I see, the closure function will be defined then immediately invoked. What's going on with that? As in:
function (){.......}();

If this was explained above, I missed it.