How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?

I have seen the Scheme example given on Wikipedia, but unfortunately it did not help.

391 upvote
  flag
My problem with these and many answers is that they approach it from an abstract, theoretical perspective, rather than starting with explaining simply why closures are necessary in Javascript and the practical situations in which you use them. You end up with a tl;dr article that you have to slog through, all the time thinking, "but, why?". I would simply start with: closures are a neat way of dealing with the following two realities of JavaScript: a. scope is at the function level, not the block level and, b. much of what you do in practice in JavaScript is asynchronous/event driven. – Jeremy Burton
53 upvote
  flag
@Redsandro For one, it makes event-driven code a lot easier to write. I might fire a function when the page loads to determine specifics about the HTML or available features. I can define and set a handler in that function and have all that context info available every time the handler is called without having to re-query it. Solve the problem once, re-use on every page where that handler is needed with reduced overhead on handler re-invocation. You ever see the same data get re-mapped twice in a language that doesn't have them? Closures make it a lot easier to avoid that sort of thing. – Erik Reppen
1 upvote
  flag
@Erik Reppen thanks for the answer. Actually, I was curious about the benefits of this hard to read closure code as opposed to Object Literal which reuses itself and reduces overhead just the same, yet requires 100% less wrapping code. – Redsandro
6 upvote
  flag
For Java programmers, the short answer is that it's the function equivalent of an inner class. An inner class also holds an implicit pointer to an instance of the outer class, and is used for much the same purpose (that is, creating event handlers). – Boris van Schooten
2 upvote
  flag
Understood this much better from here: javascriptissexy.com/understand-javascript-closures-with-eas‌​e. Still needed a closure on closure after reading the other answers. :) – Akhoy
8 upvote
  flag
I found this practical example to be very useful: youtube.com/watch?v=w1s9PgtEoJs – Abhi
1 upvote
  flag
You can start learning about closure in the given website. javascriptissexy.com/understand-javascript-closures-with-eas‌​e – zeeshan
upvote
  flag
@JeremyBurton I'm sure "a. scope is at the function level, not the block level and, b. much of what you do in practice in JavaScript is asynchronous/event driven" sounds pretty abstact and theoretical to all the n00bs who apparently have so much trouble understanding closures ;) – Andy
upvote
  flag
Practical situation in which you use closures: youtu.be/ya4UHuXNygM?t=27m36s – Will White

88 Answers 11

up vote 5458 down vote accepted

JavaScript closures for beginners

Submitted by Morris on Tue, 2006-02-21 10:19. Community-edited since.

Closures are not magic

This page explains closures so that a programmer can understand them — using working JavaScript code. It is not for gurus or 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 mainstream language, and who can read the following JavaScript function:

function sayHello(name) {
  var text = 'Hello ' + name;
  var say = function() { console.log(text); }
  say();
}
sayHello('Joe');

An example of a closure

Two one sentence summaries:

  • A closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result.

  • Or, a closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!).

The following code returns a reference to a function:

function sayHello2(name) {
  var text = 'Hello ' + name; // Local variable
  var say = function() { console.log(text); }
  return say;
}
var say2 = sayHello2('Bob');
say2(); // logs "Hello Bob"

Most JavaScript programmers will understand how a reference to a function is returned to a variable (say2) in the above code. If you don't, then you need to look at that before you can learn closures. A programmer using C would think of the function as returning a pointer to a function, and that the variables say 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() { console.log(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 accessible because the stack-frame is destroyed.

In JavaScript, if you declare a function within another function, then the local variables can remain accessible 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() { console.log(text); } // Output of say2.toString();

Looking at the output of say2.toString(), we can see that the code refers to the variable text. The anonymous function can reference text which holds the value 'Hello Bob' 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 it becomes clear 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 weird 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 = 42;
  var say = function() { console.log(num); }
  num++;
  return say;
}
var sayNumber = say667();
sayNumber(); // logs 43

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().

var gLogNumber, gIncreaseNumber, gSetNumber;
function setupSomeGlobals() {
  // Local variable that ends up within closure
  var num = 42;
  // Store some references to functions as global variables
  gLogNumber = function() { console.log(num); }
  gIncreaseNumber = function() { num++; }
  gSetNumber = function(x) { num = x; }
}

setupSomeGlobals();
gIncreaseNumber();
gLogNumber(); // 43
gSetNumber(5);
gLogNumber(); // 5

var oldLog = gLogNumber;

setupSomeGlobals();
gLogNumber(); // 42

oldLog() // 5

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 call setupSomeGlobals() again, then a new closure (stack-frame!) is created. The old gLogNumber, 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' + i;
        result.push( function() {console.log(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]();
    }
}

 testList() //logs "item2 undefined" 3 times

The line result.push( function() {console.log(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() {console.log(item + ' ' + list[i])};
result.push(pointer);

Note that when you run the example, "item2 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 'item2'). Note we are indexing from 0 hence item has a value of item2. And the i++ will increment i to the value 3.

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 same scope (JavaScript does variable hoisting). Also sayAlice()() just directly calls the function reference returned from sayAlice() — it is exactly the same as what was done previously but without the temporary variable.

function sayAlice() {
    var say = function() { console.log(alice); }
    // Local variable that ends up within closure
    var alice = 'Hello Alice';
    return say;
}
sayAlice()();// logs "Hello Alice"

Tricky: note also that the say 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);
        console.log('num: ' + num +
            '; anArray: ' + anArray.toString() +
            '; ref.someVar: ' + ref.someVar + ';');
      }
}
obj = {someVar: 4};
fn1 = newClosure(4, obj);
fn2 = newClosure(5, obj);
fn1(1); // num: 5; anArray: 1,2,3,5; ref.someVar: 4;
fn2(1); // num: 6; anArray: 1,2,3,6; ref.someVar: 4;
obj.someVar++;
fn1(2); // num: 7; anArray: 1,2,3,5,7; ref.someVar: 5;
fn2(2); // num: 8; anArray: 1,2,3,6,8; ref.someVar: 5;

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 new Function(…) (the Function constructor) inside a function, it does not create a closure. (The new function cannot reference the local variables of the outer function.)
  • A closure in JavaScript is like keeping a copy of 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 an 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 learned 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.


Original post by Morris can be found in the Internet Archive.

84 upvote
  flag
Brillant. I espacially love : "A closure in JavaScript is like keeping a copy of the all the local variables, just as they were when a function exited." – e-satis
upvote
  flag
A good link to a clearly popular answer. The author takes the brave step of using analogies to things not entirely accurate in Javascript terms but fit the a mental model already existing in the minds many programmers such as Function calls create stake frames. – AnthonyWJones
23 upvote
  flag
@e-satis - Brilliant as it may seem, "a copy of all the local variables, just as they were when the function exited" is misleading. It suggests that the values of the variables are copied, but really it is the set of variables themselves which doesn't change after the function is called (except for 'eval' maybe: blog.rakeshpai.me/2008/10/…). It suggests that the function must return before the closure is created, but it need not return before the closure can be used as a closure. – dlaliberte
9 upvote
  flag
So can we say this for closures: whenever a function is declared inside a function, the outer function is in scope for the inner function until the inner function is in scope! – Pawan
49 upvote
  flag
This sounds nice: "A closure in JavaScript is like keeping a copy of the all the local variables, just as they were when a function exited." But it is misleading for a couple reasons. (1) The function call does not have to exit in order to create a closure. (2) It is not a copy of the values of the local variables but the variables themselves. (3) It doesn't say who has access to these variables. – dlaliberte
16 upvote
  flag
Example 5 shows a "gotcha" where the code doesn't work as intended. But it doesn't show how to fix it. This other answer shows a way to do it. – Matt
upvote
  flag
would it be a fix for the 'list loop' to return the alert function on the result.push array? – netusco
112 upvote
  flag
I like how this post starts off with big bold letters saying "Closures Are Not Magic" and ends its first example with "The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in". – Andrew Macheret
upvote
  flag
For example 7, why doesn't z = newClosure(4, obj)(2000); z(); work? Is it because function(x) is the return? – Mark C.
upvote
  flag
@Invent-Animate yes, the first thing the returned function tries to do is increment num by x, which is undefined if you don't pass a parameter. I hope that made sense. – Joel Anair
upvote
  flag
@JoelAnair That makes perfect sense. But I thought adding (2000) after the newClosure(4, obj) call would pass the parameter. Thanks for answering my question! – Mark C.
1 upvote
  flag
@Invent-Animate ah, I see. I read your question wrong. What that (2000) does is immediately call the function returned by newClosure, passing in 2000. So you'd see the alert, but since that returned function doesn't itself return a value, z gets assigned the value undefined, and you'll get an error when trying to invoke it. – Joel Anair
3 upvote
  flag
Example #3 is mixing closures with javascripts hoisting. Now I think explaining only closures is difficult enough without bringing in the hoisting behaviour. This helped me the most: Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created. from developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – caramba
1 upvote
  flag
Perhaps Morris provided the minimal description length (MDL) answer to what a closure is by saying: "a closure is the local variables for a function — kept alive after the function has returned" – jb1
4 upvote
  flag
I think this is a terrible answer, because it leaves out why closures are great. It's like listening to someone who's used to driving on the right side of the road expound on how driving on the left is for them, detailing every accident they're likely to be in/cause, without awareness that their frame of mind may be a key culprit. It may satisfy as an answer for dummies already tainted by other languages, but even there I think it fails, because it makes people run away screaming, which is a shame and undeserved. See better answers below. – jib
upvote
  flag
Brilliantly explained. The one thing I'm missing is what happens to Objects passed to the creating function. – Scheintod
upvote
  flag
The first summary of "Two one sentence summaries" is kind of confusing to me; "a closure is the local variables for a function — kept alive after the function has returned". So, it that function "sayHello" or the abstract function, "function() { console.log(text) }"? It seems it's the latter, but it feels little ambiguous to noobies like me. And I think "local variables" should be "local variable". If not, correct me please. – user3290525
upvote
  flag
Great post, but I still did not get why it is needed? I mean in languages like C or Java this closure does not exist as I understand. Could you please give example of standard implementation of something and implementation with closure where it will be visible, that closure much better for some cases? like this sayHello2 function from example above can be implemented as:⁠⁠ function sayHello2(name) { var text = 'Hello ' + name; console.log(text); } It will log to output Hello and name. What is the benefits of using closure with the same result? – Zlelik
1 upvote
  flag
@Zlelik one example of a use case for closures is adding event handlers to elements that need access to specific objects. This can be difficult when those objects are not in the global namespace because that event handler might run at any point in the future. Another good use for closures is creating private members : javascript.crockford.com/private.html – Joel Anair
upvote
  flag
@Zlelik That's called an immediately invoked function expression, or IIFE. The main advantage of it is that, due to function scope, variables declared inside an IIFE don't exist in the global scope (or in whatever other scope the IIFE is declared in). This allows something like namespacing, which is otherwise not a feature in JavaScript. More info here: en.wikipedia.org/wiki/Immediately-invoked_function_expressio‌​n – Joel Anair
upvote
  flag
@hariszhr I promise you that if I can (sort of) wrap my head around closures you can, too. It's worth it if you are doing any kind of serious JavaScript development. – Joel Anair
1 upvote
  flag
This was all CRYSTAL CLEAR when I looked up the .sort function. It can take a function as a parameter. Then this all make sense.: javascriptkit.com/javatutors/arraysort.shtml – Clay Nichols
3 upvote
  flag
ECMAScript 6 may change something in this great article about closure. For example, if you use let i = 0 instead of var i = 0 in Example 5, then the testList() will print what you want originally. – Nier
upvote
  flag
I was looking for some material to teach others JavaScript. This was an excellent, straightforward explanation that a C programmer can understand. Love the explanation with the stack-frame example. Thank you! – Bran
3 upvote
  flag
Why do example 3 and 4 say they will log 667. When I run it I get either 43 or 42 respectively – Muntasir Alam
upvote
  flag
After reading a few answers here I think I understand what a closure is, and why JavaScript needs them. What I don't understand, however, is why a developer needs to know how they work. Do we? – Ruud Lenders
upvote
  flag
@RuudLenders I think the most important reason to understand closures is for writing event handlers and dealing with async operations. There are lots of other reasons but those are the ones that come up the most for me. – Joel Anair
upvote
  flag
The statement with example 7 is misleading. Each call to the outer function creates a new closure with respect to the declaration of the inner function. All of the calls to the outer function are using the same closure with respect to its declaration. – Rozwel
upvote
  flag
Be aware: using eval in a function puts ALL outer-scope variables into the closure -- the compiler is not able to predict which will be needed later, it cannot optimize away unused variables and thus the eval may have impact on the performance. This might be a desired effect in some debugging scenarios. See //allinonescript.com/a/17809716/1859442 – Benjamin
upvote
  flag
One of possible options of fixing 'gotcha' in example 5 is to create an additional context: function buildList(list) { var result = []; for (var i = 0; i < list.length; i++) { result.push((function(k){var item = 'item' + k; return function() { print(item + ' ' + list[k]); }})(i)); } return result; } – user2598794
upvote
  flag
About Example 5. How would you go about doing that though? I ve tried function buildList(list) { var result = []; for (var i = 0; i < list.length; i++) { var item = 'item' + i; result.push( function() {****var item = item;***** console.log(item + ' ' + list[i])} ); } return result; } But that still doesnt work. I would expect as we're declaring a new variable item in the anonymous function scope that it would work but it just doesnt for some reason. – George Avgoustis
upvote
  flag
Just a question that doesn't deserve it's own question: When you say that creating a function inside a function you create a closure which copies the local variables. Doesn't that cause bloating when we're constantly creating functions inside functions like in jQuery (document.ready(function...))?? Sorry for the (maybe) dumb question. I'm a beginner in JS. – workoverflow

A closure is much like an object. It gets instantiated whenever you call a function.

The scope of a closure in JavaScript is lexical, which means that everything that is contained within the function the closure belongs to, has access to any variable that is in it.

A variable is contained in the closure if you

  1. assign it with var foo=1; or
  2. just write var foo;

If an inner function (a function contained inside another function) accesses such a variable without defining it in its own scope with var, it modifies the content of the variable in the outer closure.

A closure outlives the runtime of the function that spawned it. If other functions make it out of the closure/scope in which they are defined (for instance as return values), those will continue to reference that closure.

Example

 function example(closure) {
   // define somevariable to live in the closure of example
   var somevariable = 'unchanged';

   return {
     change_to: function(value) {
       somevariable = value;
     },
     log: function(value) {
       console.log('somevariable of closure %s is: %s',
         closure, somevariable);
     }
   }
 }

 closure_one = example('one');
 closure_two = example('two');

 closure_one.log();
 closure_two.log();
 closure_one.change_to('some new value');
 closure_one.log();
 closure_two.log();

Output

somevariable of closure one is: unchanged
somevariable of closure two is: unchanged
somevariable of closure one is: some new value
somevariable of closure two is: unchanged
46 upvote
  flag
Wow, never knew you could use string substitutions in console.log like that. If anyone else is interested there are more: developer.mozilla.org/en-US/docs/DOM/… – Flash
5 upvote
  flag
Variables that are in the function's parameter list are also part of the closure (e.g. not just limited to var). – Thomas Eding

Closures are hard to explain because they are used to make some behaviour work that everybody intuitively expects to work anyway. I find the best way to explain them (and the way that I learned what they do) is to imagine the situation without them:

    var bind = function(x) {
        return function(y) { return x + y; };
    }
    
    var plus5 = bind(5);
    console.log(plus5(3));

What would happen here if JavaScript didn't know closures? Just replace the call in the last line by its method body (which is basically what function calls do) and you get:

console.log(x + 3);

Now, where's the definition of x? We didn't define it in the current scope. The only solution is to let plus5 carry its scope (or rather, its parent's scope) around. This way, x is well-defined and it is bound to the value 5.

21 upvote
  flag
I agree. Giving the functions meaningful names instead of the traditional "foobar" ones also helps me a lot. Semantics counts. – Ishmael
40 upvote
  flag
so in a pseudo-language, it is basically like alert(x+3, where x = 5). The where x = 5 is the closure. Am I right? – Jus12
16 upvote
  flag
@Jus12: exactly. Behind the scenes, a closure is just some space where current variable values (“bindings”) are stored, as in your example. – Konrad Rudolph
9 upvote
  flag
This is exactly the sort of example that misleads many people into thinking that it is the values that are used in the returned function, not the changeable variable itself. If it were changed to "return x += y", or better yet both that and another function "x *= y", then it would be clear that nothing is being copied. For people used to stack frames, imagine using heap frames instead, which can continue to exist after the function returns. – Matt
9 upvote
  flag
@Matt I disagree. An example is not supposed to exhaustively document all properties. It is meant to be reductive and illustrate the salient feature of a concept. The OP asked for a simple explanation (“for a six year-old”). Take the accepted answer: It utterly fails at delivering a concise explanation, precisely because it attempts to be exhaustive. (I do agree with you that it’s an important property of JavaScript that binding is by reference rather than by value … but again, a successful explanation is one that reduces to the bare minimum.) – Konrad Rudolph
upvote
  flag
@KonradRudolph I like the style and brevity of your example. I simply recommend changing it slightly so that the final part, "The only solution is...", becomes true. Currently there is in fact another, simpler solution to your scenario, which does not correspond to javascript continuations, and does correspond to a common misconception about what continuations are. Thus the example in its current form is dangerous. This doesn't have to do with exhaustively listing properties, it has to do with understanding what the x is in the returned function, which is after all the main point. – Matt
upvote
  flag
@Matt Hmm, I’m not sure I fully understand you but I begin to see that you may have a valid point. Since the comments are too short, could you maybe explain what you mean in a gist/pastie or in a chat room? Thanks. – Konrad Rudolph
upvote
  flag
@KonradRudolph My point is essentially the same as example 5 of this answer, or bullet 2 of this answer. I think the x+=y modification would clarify this. Ideally, the example would even demonstrate that multiple inner functions use the same variables, while multiple calls to the outer function create different variables, but I admit this would complicate the answer. – Matt
upvote
  flag
@Matt That’s not enough: if I use x+=y in my example then the outer value will not get modified – even if you use a variable instead of a value: jsfiddle.net/CJR85/2 – this is logical since the scope that’ll get shared is that of the incrementer function call, and not the outer scope where myvar is defined (which itself is copied). The loop example is different since an anonymous function is created in the same scope repeatedly. I’m still thinking about a concise example for my answer. The loop case is a great caveat but doesn’t fit my answer which aims to show the intuition. – Konrad Rudolph
1 upvote
  flag
@KonradRudolph I think I wasn't clear about the purpose of the x+=y. The purpose was just to show that repeated calls to the returned function keep using the same variable x (as opposed to the same value, which people imagine is "inserted" when the function is created). This is like the first two alerts in your fiddle. The purpose of an additional function x*=y would be to show that multiple returned functions all share the same x. – Matt

Whenever you see the function keyword within another function, the inner function has access to variables in the outer function.

function foo(x) {
  var tmp = 3;

  function bar(y) {
    console.log(x + y + (++tmp)); // will log 16
  }

  bar(10);
}

foo(2);

This will always log 16, because bar can access the x which was defined as an argument to foo, and it can also access tmp from foo.

That is a closure. A function doesn't have to return in order to be called a closure. Simply accessing variables outside of your immediate lexical scope creates a closure.

function foo(x) {
  var tmp = 3;

  return function (y) {
    console.log(x + y + (++tmp)); // will also log 16
  }
}

var bar = foo(2); // bar is now a closure.
bar(10);

The above function will also log 16, because bar can still refer to x and tmp, even though it is no longer directly inside the scope.

However, since tmp is still hanging around inside bar's closure, it is also being incremented. It will be incremented each time you call bar.

The simplest example of a closure is this:

var a = 10;
function test() {
  console.log(a); // will output 10
  console.log(b); // will output 6
}
var b = 6;
test();

When a JavaScript function is invoked, a new execution context is created. Together with the function arguments and the parent object, this execution context also receives all the variables declared outside of it (in the above example, both 'a' and 'b').

It is possible to create more than one closure function, either by returning a list of them or by setting them to global variables. All of these will refer to the same x and the same tmp, they don't make their own copies.

Here the number x is a literal number. As with other literals in JavaScript, when foo is called, the number x is copied into foo as its argument x.

On the other hand, JavaScript always uses references when dealing with objects. If say, you called foo with an object, the closure it returns will reference that original object!

function foo(x) {
  var tmp = 3;

  return function (y) {
    console.log(x + y + tmp);
    x.memb = x.memb ? x.memb + 1 : 1;
    console.log(x.memb);
  }
}

var age = new Number(2);
var bar = foo(age); // bar is now a closure referencing age.
bar(10);

As expected, each call to bar(10) will increment x.memb. What might not be expected, is that x is simply referring to the same object as the age variable! After a couple of calls to bar, age.memb will be 2! This referencing is the basis for memory leaks with HTML objects.

15 upvote
  flag
@feeela: Yes, every JS function creates a closure. Variables that are not referenced will likely be made eligible for garbage collection in modern JS engines, but it doesn't change the fact that when you create an execution context, that context has a reference to the enclosing execution context, and its variables, and that function is an object that has potential to be relocated to a different variable scope, while retaining that original reference. That's the closure. – Crazy Train
upvote
  flag
@Ali I've just discovered that the jsFiddle I've provided doesn't actually prove anything, since the delete fails. Nevertheless, the lexical environment that the function will carry around as [[Scope]] (and ultimately use as a base for it's own lexical environment when invoked) is determined when the statement that defines the function is executed. This means that the function is closing over the ENTIRE contents of the executing scope, regardless of which values it actually refers to and whether it escapes the scope. Please look at sections 13.2 and 10 in the spec – Asad Saeeduddin
4 upvote
  flag
This was a good answer until it tried explaining primitive types and references. It gets that completely wrong and talks about literals being copied, which really has nothing to do with anything. – Ryan
6 upvote
  flag
Closures are JavaScript's answer to class-based, object oriented programing. JS is not class based, so one had to find another way to implement some things which could not be implemented otherwise. – Barth Zalewski
upvote
  flag
this should be the accepted answer. The magic never happens in the inner function. It happens when assign the outer function to a variable. This creates a new execution context for the inner function, so the "private variable" can be accumulated. Of course it can since the variable the outer function assigned to has maintained the context. The first answer just make the whole thing more complex without explaining what really happens there. – Albert Gao

A closure is where an inner function has access to variables in its outer function. That's probably the simplest one-line explanation you can get for closures.

32 upvote
  flag
That's only half the explanation. The important thing to note about closures is that if the inner function is still being referred to after the outer function has exited, the old values of the outer function are still available to the inner one. – pcorcoran
20 upvote
  flag
Actually, it is not the old values of the outer function that are available to the inner function, but the old variables, which might have new values if some function was able to change them. – dlaliberte

This is an attempt to clear up several (possible) misunderstandings about closures that appear in some of the other answers.

  • A closure is not only created when you return an inner function. In fact, the enclosing function does not need to return at all in order for its closure to be created. You might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be called immediately or any time later. Therefore, the closure of the enclosing function is probably created as soon as the enclosing function is called since any inner function has access to that closure whenever the inner function is called, before or after the enclosing function returns.
  • A closure does not reference a copy of the old values of variables in its scope. The variables themselves are part of the closure, and so the value seen when accessing one of those variables is the latest value at the time it is accessed. This is why inner functions created inside of loops can be tricky, since each one has access to the same outer variables rather than grabbing a copy of the variables at the time the function is created or called.
  • The "variables" in a closure include any named functions declared within the function. They also include arguments of the function. A closure also has access to its containing closure's variables, all the way up to the global scope.
  • Closures use memory, but they don't cause memory leaks since JavaScript by itself cleans up its own circular structures that are not referenced. Internet Explorer memory leaks involving closures are created when it fails to disconnect DOM attribute values that reference closures, thus maintaining references to possibly circular structures.
19 upvote
  flag
By the way, I added this "answer" with clarifications not to address the original question directly. Instead, I hope that any simple answer (for a 6-year old) doesn't introduce incorrect notions about this complex subject. E.g. the popular wiki-answer above says "A closure is when you return the inner function." Aside from being grammatically wrong, that is technically wrong. – dlaliberte
13 upvote
  flag
James, I said the closure is "probably" created at the time of the call of the enclosing function because it is plausible that an implementation could defer the creation of a closure until sometime later, when it decides a closure is absolutely needed. If there is no inner function defined in the enclosing function, then no closure will be needed. So maybe it could wait until the first inner function gets created to then create a closure out of the enclosing function's call context. – dlaliberte
upvote
  flag
First point is not correct. A closure is definitely not formed as soon as an outer function is called. An outer function must have completed and returned for a closure to be formed, otherwise all you have is a bog standard call stack of one or more functions. The only other thing you need for a closure to be formed is an enduring external reference to an inner function. The external reference may be formed by returning an inner function and assigning it, or by other means. In browser-based javascript "other means" is typically the attachment of an inner function as an event handler. – Beetroot-Beetroot
7 upvote
  flag
@Beetroot-Beetroot Suppose we have an inner function that is passed to another function where it is used before the outer function returns, and suppose we also return the same inner function from the outer function. It is identically the same function in both cases, but you are saying that before the outer function returns, the inner function is "bound" to the call stack, whereas after it returns, the inner function is suddenly bound to a closure. It behaves identically in both cases; the semantics are identical, so aren't you just talking about implementation details? – dlaliberte
upvote
  flag
dlaliberte, this is interesting and you have caused me a hard think. What you describe in your opening sentence is certainly a feature of js functions being first class objects and that they maintain access to the environment (the lexical scope) in which they were defined regardless of where they are eventually executed. In my opinion, all of that is a prerequisite for closure but not closure itself, though some definitions of "closure" would have us believe otherwise. The reason I say that a closure is not formed before the outer function has returned is very simple - nothing has closed! – Beetroot-Beetroot
upvote
  flag
The outer function is still naturally alive and kicking in exactly the same way it would be if there was no inner function or if an inner function were executed internally. The environment created by execution of the outer function is not yet on "life support", a condition that occurs only if a reference to at least one inner function is maintained somewhere in an external scope (including the DOM) and after the outer function has completed and returned. (Please note that "returned" in this context does not mean that the outer function necessarily returns an inner function; ... – Beetroot-Beetroot
upvote
  flag
... the external reference could have been be put in place by other means, eg. by attaching an inner function as a DOM event handler). At that point, YES, a closure is formed. There's nothing sudden about it - the only thing that differs from the completion of a non-closure-forming function is that garbage collection is suppressed. Going back to the original point in your post above, I think a better statement would be that at a certain point in the execution of an outer function, the formation of a closure may be inevitable, but that a closure is not formed until the outer function returns. – Beetroot-Beetroot
5 upvote
  flag
@Beetroot-Beetroot, thanks for your feedback, and I am glad I got you thinking. I still don't see any semantic difference between the outer function's live context and that same context when it becomes a closure as the function returns (if I understand your definition). The inner function doesn't care. Garbage collection doesn't care since the inner function maintains a reference to the context/closure either way, and the caller of the outer function just drops its reference to the call context. But it is confusing to people, and perhaps better to just call it a call context. – dlaliberte
upvote
  flag
dlaliberte, stick "closures and garbage collection" into Google and you will rapidly find evidence if not proof that GC (or rather the suppression of it) is absolutely central to the concept of closures. – Beetroot-Beetroot
upvote
  flag
And in case you don't find it , here's what I believe to be THE seminal article on (javascript) closures. It made me realise that you can't really understand closures until you know how they arise and my understanding changed completely. Before I read this article, I was almost precisely where you are now. Ignore the definition provided at the top - it's correct but incomplete. I had to read the whole article through, maybe 2 or 3 times, before I got it. – Beetroot-Beetroot
7 upvote
  flag
That article is difficult to read, but I think it actually supports what I am saying. It says: "A closure is formed by returning a function object [...] or by directly assigning a reference to such a function object to, for example, a global variable." I don't mean that GC is irrelevant. Rather, because of GC, and because the inner function is attached to the outer function's call context (or [[scope]] as the article says), then it doesn't matter whether the outer function call returns because that binding with the inner function is the important thing. – dlaliberte
1 upvote
  flag
Furthermore, the outer function probably doesn't know whether the inner function eventually gets assigned to some external variable, or object property, or array element, possibly by being passed as an argument to another function call. By the time the outer function returns, it doesn't know whether or not the inner function will survive, so why is it meaningful to say the closure is created at that time? GC will eventually clean up the unreferenced outer function call context, after all refs to the inner function have been GCed. – dlaliberte
2 upvote
  flag
Great answer! One thing you should add is that all functions close over the entire contents of the executing scope in which they are defined. It does not matter whether they refer to some or none of the variables from the parent scope: a reference to the lexical environment of the parent scope is stored as [[Scope]] unconditionally. This can be seen from the section on function creation in the ECMA spec. – Asad Saeeduddin

Example for the first point by dlaliberte:

A closure is not only created when you return an inner function. In fact, the enclosing function does not need to return at all. You might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be used immediately. Therefore, the closure of the enclosing function probably already exists at the time that enclosing function was called since any inner function has access to it as soon as it is called.

var i;
function foo(x) {
    var tmp = 3;
    i = function (y) {
        console.log(x + y + (++tmp));
    }
}
foo(2);
i(3);
4 upvote
  flag
FYI: running the above shows=> 9 – JJ Rohrer
upvote
  flag
Small clarification about a possible ambiguity. When I said "In fact, the enclosing function does not need to return at all." I didn't mean "return no value" but "still active". So the example doesn't show that aspect, though it shows another way the inner function can be passed to the outer scope. The main point I was trying to make is about the time of creation of the closure (for the enclosing function), since some people seem to think it happens when the enclosing function returns. A different example is required to show that the closure is created when a function is called. – dlaliberte

Can you explain closures to a 5-year-old?*

I still think Google's explanation works very well and is concise:

/*
*    When a function is defined in another function and it
*    has access to the outer function's context even after
*    the outer function returns.
*
* An important concept to learn in JavaScript.
*/

function outerFunction(someNum) {
    var someString = 'Hey!';
    var content = document.getElementById('content');
    function innerFunction() {
        content.innerHTML = someNum + ': ' + someString;
        content = null; // Internet Explorer memory leak for DOM reference
    }
    innerFunction();
}

outerFunction(1);​

Proof that this example creates a closure even if the inner function doesn't return

*A C# question

18 upvote
  flag
If you read the description, you'll see that your example is not correct. The call to innerFunction is within the scope of the outer function, and not, as the description says, after the outer function returns. Whenever you call outerFunction, a new innerFunction is created and then used in scope. – Moss
8 upvote
  flag
@Moss that's not my comments, they're a Google developer's – Chris S
7 upvote
  flag
Seeing that innerFunction is not referenced outside outerFunction's scope, is the interpreter smart enough to see that it needs no closure? – syockit
8 upvote
  flag
The code is "correct", as an example of a closure, even though it doesn't address the part of the comment about using the closure after the outerFunction returns. So it is not a great example. There are many other ways a closure could be used that don't involve returning the innerFunction. e.g. innerFunction could be passed to another function where it is called immediately or stored and called some time later, and in all cases, it has access to the outerFunction context that was created when it was called. – dlaliberte
4 upvote
  flag
@syockit No, Moss is wrong. A closure is created regardless of whether the function ever escapes the scope in which it is defined, and an unconditionally created reference to the parent's lexical environment makes all variables in the parent scope available for all functions, regardless of whether they are invoked outside or inside the scope in which they were created. – Asad Saeeduddin

I wrote a blog post a while back explaining closures. Here's what I said about closures in terms of why you'd want one.

Closures are a way to let a function have persistent, private variables - that is, variables that only one function knows about, where it can keep track of info from previous times that it was run.

In that sense, they let a function act a bit like an object with private attributes.

Full post:

So what are these closure thingys?

upvote
  flag
So could the main benefit of closures could be emphasized with this example? Say I have a function emailError(sendToAddress, errorString) I could then say devError = emailError("devinrhode2@googmail.com", errorString) and then have my own custom version of a shared emailError function? – Devin G Rhode
6 upvote
  flag
After shoveling my way through a whole lot of 'splaining, I started to finally understand what they were for. I thought to myself "oh, its like private variables in an object?" and bam. This was next answer I read. – Mixologic

JavaScript functions can access their:

  1. Arguments
  2. Locals (that is, their local variables and local functions)
  3. Environment, which includes:
    • globals, including the DOM
    • anything in outer functions

If a function accesses its environment, then the function is a closure.

Note that outer functions are not required, though they do offer benefits I don't discuss here. By accessing data in its environment, a closure keeps that data alive. In the subcase of outer/inner functions, an outer function can create local data and eventually exit, and yet, if any inner function(s) survive after the outer function exits, then the inner function(s) keep the outer function's local data alive.

Example of a closure that uses the global environment:

Imagine that the Stack Overflow Vote-Up and Vote-Down button events are implemented as closures, voteUp_click and voteDown_click, that have access to external variables isVotedUp and isVotedDown, which are defined globally. (For simplicity's sake, I am referring to StackOverflow's Question Vote buttons, not the array of Answer Vote buttons.)

When the user clicks the VoteUp button, the voteUp_click function checks whether isVotedDown == true to determine whether to vote up or merely cancel a down vote. Function voteUp_click is a closure because it is accessing its environment.

var isVotedUp = false;
var isVotedDown = false;

function voteUp_click() {
  if (isVotedUp)
    return;
  else if (isVotedDown)
    SetDownVote(false);
  else
    SetUpVote(true);
}

function voteDown_click() {
  if (isVotedDown)
    return;
  else if (isVotedUp)
    SetUpVote(false);
  else
    SetDownVote(true);
}

function SetUpVote(status) {
  isVotedUp = status;
  // Do some CSS stuff to Vote-Up button
}

function SetDownVote(status) {
  isVotedDown = status;
  // Do some CSS stuff to Vote-Down button
}

All four of these functions are closures as they all access their environment.

FOREWORD: this answer was written when the question was:

Like the old Albert said : "If you can't explain it to a six-year old, you really don't understand it yourself.”. Well I tried to explain JS closures to a 27 years old friend and completely failed.

Can anybody consider that I am 6 and strangely interested in that subject ?

I'm pretty sure I was one of the only people that attempted to take the initial question literally. Since then, the question has mutated several times, so my answer may now seem incredibly silly & out of place. Hopefully the general idea of the story remains fun for some.


I'm a big fan of analogy and metaphor when explaining difficult concepts, so let me try my hand with a story.

Once upon a time:

There was a princess...

function princess() {

She lived in a wonderful world full of adventures. She met her Prince Charming, rode around her world on a unicorn, battled dragons, encountered talking animals, and many other fantastical things.

    var adventures = [];

    function princeCharming() { /* ... */ }

    var unicorn = { /* ... */ },
        dragons = [ /* ... */ ],
        squirrel = "Hello!";

    /* ... */

But she would always have to return back to her dull world of chores and grown-ups.

    return {

And she would often tell them of her latest amazing adventure as a princess.

        story: function() {
            return adventures[adventures.length - 1];
        }
    };
}

But all they would see is a little girl...

var littleGirl = princess();

...telling stories about magic and fantasy.

littleGirl.story();

And even though the grown-ups knew of real princesses, they would never believe in the unicorns or dragons because they could never see them. The grown-ups said that they only existed inside the little girl's imagination.

But we know the real truth; that the little girl with the princess inside...

...is really a princess with a little girl inside.

269 upvote
  flag
I love this explanation, truly. For those who read it and don't follow, the analogy is this: the princess() function is a complex scope containing private data. Outside the function, the private data can't be seen or accessed. The princess keeps the unicorns, dragons, adventures etc. in her imagination (private data) and the grown-ups can't see them for themselves. BUT the princess's imagination is captured in the closure for the story() function, which is the only interface the littleGirl instance exposes into the world of magic. – Patrick M
upvote
  flag
So here story is the closure but had the code been var story = function() {}; return story; then littleGirl would be the closure. At least that's the impression that I get from MDN's use of 'private' methods with closures: "Those three public functions are closures that share the same environment." – icc97
11 upvote
  flag
@icc97, yes, story is a closure referencing the environment provided within the scope of princess. princess is also another implied closure, i.e. the princess and the littleGirl would share any reference to a parents array that would exist back in the environment/scope where the littleGirl exists and the princess is defined. – Jacob Swartwood
upvote
  flag
shouldn't it be var littleGirl = new princess() ? – Merlin
upvote
  flag
That is not necessary @Lorenzo - this princess design is not a "class" but rather a "factory". – Jacob Swartwood
upvote
  flag
@Patrick M but 'adventures' is an empty array, nothing is returned from 'princess' by 'story' function. what am i missing? – user1559625
upvote
  flag
@user1559625 For the example to make sense there would be a new adventure added to the array every now and then. In the example code we only see the initialization. The point is that the outside world doesn't see all the variables in the scope of the function princess but the story function (a closure defined in the princess function) does. I personally always found this kind of metaphorical explanations very confusing, because when you don't understand something it's even harder if you have to parse trough some metaphor where you don't know what the author is getting at. – Benjamin Krupp
2 upvote
  flag
@BenjaminKrupp I've added an explicit code comment to show/imply that there are more operations within the body of princess than what's written. Unfortunately this story is now a bit out of place on this thread. Originally the question was asking to "explain JavaScript closures to a 5yr old"; my response was the only one that even attempted to do that. I don't doubt that it would've failed miserably, but at least this response might've had the chance to hold a 5yr old's interest. – Jacob Swartwood
upvote
  flag
Actually, to me this made perfect sense. And i must admit, finally understanding a JS closure by using tales of princesses and adventures makes me feel kinda weird. – Crystallize

You're having a sleep over and you invite Dan. You tell Dan to bring one XBox controller.

Dan invites Paul. Dan asks Paul to bring one controller. How many controllers were brought to the party?

function sleepOver(howManyControllersToBring) {

    var numberOfDansControllers = howManyControllersToBring;

    return function danInvitedPaul(numberOfPaulsControllers) {
        var totalControllers = numberOfDansControllers + numberOfPaulsControllers;
        return totalControllers;
    }
}

var howManyControllersToBring = 1;

var inviteDan = sleepOver(howManyControllersToBring);

// The only reason Paul was invited is because Dan was invited. 
// So we set Paul's invitation = Dan's invitation.

var danInvitedPaul = inviteDan(howManyControllersToBring);

alert("There were " + danInvitedPaul + " controllers brought to the party.");

I put together an interactive JavaScript tutorial to explain how closures work. What's a Closure?

Here's one of the examples:

var create = function (x) {
    var f = function () {
        return x; // We can refer to x here!
    };
    return f;
};
// 'create' takes one argument, creates a function

var g = create(42);
// g is a function that takes no arguments now

var y = g();
// y is 42 here

Wikipedia on closures:

In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.

Technically, in JavaScript, every function is a closure. It always has an access to variables defined in the surrounding scope.

Since scope-defining construction in JavaScript is a function, not a code block like in many other languages, what we usually mean by closure in JavaScript is a function working with nonlocal variables defined in already executed surrounding function.

Closures are often used for creating functions with some hidden private data (but it's not always the case).

var db = (function() {
    // Create a hidden object, which will hold the data
    // it's inaccessible from the outside.
    var data = {};

    // Make a function, which will provide some access to the data.
    return function(key, val) {
        if (val === undefined) { return data[key] } // Get
        else { return data[key] = val } // Set
    }
    // We are calling the anonymous surrounding function,
    // returning the above inner function, which is a closure.
})();

db('x')    // -> undefined
db('x', 1) // Set x to 1
db('x')    // -> 1
// It's impossible to access the data object itself.
// We are able to get or set individual it.

ems

The example above is using an anonymous function, which was executed once. But it does not have to be. It can be named (e.g. mkdb) and executed later, generating a database function each time it is invoked. Every generated function will have its own hidden database object. Another usage example of closures is when we don't return a function, but an object containing multiple functions for different purposes, each of those function having access to the same data.

Taking the question seriously, we should find out what a typical 6-year-old is capable of cognitively, though admittedly, one who is interested in JavaScript is not so typical.

On Childhood Development: 5 to 7 Years it says:

Your child will be able to follow two-step directions. For example, if you say to your child, "Go to the kitchen and get me a trash bag" they will be able to remember that direction.

We can use this example to explain closures, as follows:

The kitchen is a closure that has a local variable, called trashBags. There is a function inside the kitchen called getTrashBag that gets one trash bag and returns it.

We can code this in JavaScript like this:

function makeKitchen () {
  var trashBags = ['A', 'B', 'C']; // only 3 at first

  return {
    getTrashBag: function() {
      return trashBags.pop();
    }
  };
}

var kitchen = makeKitchen();

kitchen.getTrashBag(); // returns trash bag C
kitchen.getTrashBag(); // returns trash bag B
kitchen.getTrashBag(); // returns trash bag A

Further points that explain why closures are interesting:

  • Each time makeKitchen() is called, a new closure is created with its own separate trashBags.
  • The trashBags variable is local to the inside of each kitchen and is not accessible outside, but the inner function on the getTrashBag property does have access to it.
  • Every function call creates a closure, but there would be no need to keep the closure around unless an inner function, which has access to the inside of the closure, can be called from outside the closure. Returning the object with the getTrashBag function does that here.
3 upvote
  flag
Actually, confusingly, the makeKitchen function call is the actual closure, not the kitchen object that it returns. – dlaliberte
2 upvote
  flag
Having my way through the others I found this answer as the easiest way to explain about what and why the closures.is. – hyip
upvote
  flag
Too much menu and appetizer, not enough meat and potatoes. You could improve that answer with just one short sentence like: "A closure is the sealed context of a function, for lack of any scoping mechanism provided by classes." – Jacob

I know there are plenty of solutions already, but I guess that this small and simple script can be useful to demonstrate the concept:

// makeSequencer will return a "sequencer" function
var makeSequencer = function() {
    var _count = 0; // not accessible outside this function
    var sequencer = function () {
        return _count++;
    }
    return sequencer;
}

var fnext = makeSequencer();
var v0 = fnext();     // v0 = 0;
var v1 = fnext();     // v1 = 1;
var vz = fnext._count // vz = undefined

After a function is invoked, it goes out of scope. If that function contains something like a callback function, then that callback function is still in scope. If the callback function references some local variable in the immediate environment of the parent function, then naturally you'd expect that variable to be inaccessible to the callback function and return undefined.

Closures ensure that any property that is referenced by the callback function is available for use by that function, even when its parent function may have gone out of scope.

From a personal blog post:

By default, JavaScript knows two types of scopes: global and local.

var a = 1;

function b(x) {
    var c = 2;
    return x * c;
}

In the above code, variable a and function b are available from anywhere in the code (that is, globally). Variable c is only available within the b function scope (that is, local). Most software developers won't be happy with this lack of scope flexibility, especially in large programs.

JavaScript closures help solving that issue by tying a function with a context:

function a(x) {
    return function b(y) {
        return x + y;
    }
}

Here, function a returns a function called b. Since b is defined within a, it automatically has access to whatever is defined in a, that is, x in this example. This is why b can return x + y without declaring x.

var c = a(3);

Variable c is assigned the result of a call to a with parameter 3. That is, an instance of function b where x = 3. In other words, c is now a function equivalent to:

var c = function b(y) {
    return 3 + y;
}

Function b remembers that x = 3 in its context. Therefore:

var d = c(4);

will assign the value 3 + 4 to d, that is 7.

Remark: If someone modifies the value of x (say x = 22) after the instance of function b has been created, this will be reflected in b too. Hence a later call to c(4) would return 22 + 4, that is 26.

Closures can also be used to limit the scope of variables and methods declared globally:

(function () {
    var f = "Some message";
    alert(f);
})();

The above is a closure where the function has no name, no argument and is called immediately. The highlighted code, which declares a global variable f, limits the scopes of f to the closure.

Now, there is a common JavaScript caveat where closures can help:

var a = new Array();

for (var i=0; i<2; i++) {
    a[i]= function(x) { return x + i ; }
}

From the above, most would assume that array a would be initialized as follows:

a[0] = function (x) { return x + 0 ; }
a[1] = function (x) { return x + 1 ; }
a[2] = function (x) { return x + 2 ; }

In reality, this is how a is initialized, since the last value of i in the context is 2:

a[0] = function (x) { return x + 2 ; }
a[1] = function (x) { return x + 2 ; }
a[2] = function (x) { return x + 2 ; }

The solution is:

var a = new Array();

for (var i=0; i<2; i++) {
    a[i]= function(tmp) {
        return function (x) { return x + tmp ; }
    } (i);
}

The argument/variable tmp holds a local copy of the changing value of i when creating function instances.

A function in JavaScript is not just a reference to a set of instructions (as in C language), but it also includes a hidden data structure which is composed of references to all nonlocal variables it uses (captured variables). Such two-piece functions are called closures. Every function in JavaScript can be considered a closure.

Closures are functions with a state. It is somewhat similar to "this" in the sense that "this" also provides state for a function but function and "this" are separate objects ("this" is just a fancy parameter, and the only way to bind it permanently to a function is to create a closure). While "this" and function always live separately, a function cannot be separated from its closure and the language provides no means to access captured variables.

Because all these external variables referenced by a lexically nested function are actually local variables in the chain of its lexically enclosing functions (global variables can be assumed to be local variables of some root function), and every single execution of a function creates new instances of its local variables, it follows that every execution of a function returning (or otherwise transferring it out, such as registering it as a callback) a nested function creates a new closure (with its own potentially unique set of referenced nonlocal variables which represent its execution context).

Also, it must be understood that local variables in JavaScript are created not on the stack frame, but on the heap and destroyed only when no one is referencing them. When a function returns, references to its local variables are decremented, but they can still be non-null if during the current execution they became part of a closure and are still referenced by its lexically nested functions (which can happen only if the references to these nested functions were returned or otherwise transferred to some external code).

An example:

function foo (initValue) {
   //This variable is not destroyed when the foo function exits.
   //It is 'captured' by the two nested functions returned below.
   var value = initValue;

   //Note that the two returned functions are created right now.
   //If the foo function is called again, it will return
   //new functions referencing a different 'value' variable.
   return {
       getValue: function () { return value; },
       setValue: function (newValue) { value = newValue; }
   }
}

function bar () {
    //foo sets its local variable 'value' to 5 and returns an object with
    //two functions still referencing that local variable
    var obj = foo(5);

    //Extracting functions just to show that no 'this' is involved here
    var getValue = obj.getValue;
    var setValue = obj.setValue;

    alert(getValue()); //Displays 5
    setValue(10);
    alert(getValue()); //Displays 10

    //At this point getValue and setValue functions are destroyed
    //(in reality they are destroyed at the next iteration of the garbage collector).
    //The local variable 'value' in the foo is no longer referenced by
    //anything and is destroyed too.
}

bar();

Closures are a means through which inner functions can refer to the variables present in their outer enclosing function after their parent functions have already terminated.

// A function that generates a new function for adding numbers.
function addGenerator( num ) {
    // Return a simple function for adding two numbers
    // with the first number borrowed from the generator
    return function( toAdd ) {
        return num + toAdd
    };
}

// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number.
var addFive = addGenerator( 5 );
// We can see here that the result of the addFive function is 9,
// when passed an argument of 4.
alert( addFive( 4 ) == 9 );

The Straw Man

I need to know how many times a button has been clicked and do something on every third click...

Fairly Obvious Solution

// Declare counter outside event handler's scope
var counter = 0;
var element = document.getElementById('button');

element.addEventListener("click", function() {
  // Increment outside counter
  counter++;

  if (counter === 3) {
    // Do something every third time
    console.log("Third time's the charm!");

    // Reset counter
    counter = 0;
  }
});
<button id="button">Click Me!</button>

Now this will work, but it does encroach into the outer scope by adding a variable, whose sole purpose is to keep track of the count. In some situations, this would be preferable as your outer application might need access to this information. But in this case, we are only changing every third click's behavior, so it is preferable to enclose this functionality inside the event handler.

Consider this option

var element = document.getElementById('button');

element.addEventListener("click", (function() {
  // init the count to 0
  var count = 0;

  return function(e) { // <- This function becomes the click handler
    count++; //    and will retain access to the above `count`

    if (count === 3) {
      // Do something every third time
      console.log("Third time's the charm!");

      //Reset counter
      count = 0;
    }
  };
})());
<button id="button">Click Me!</button>

Notice a few things here.

In the above example, I am using the closure behavior of JavaScript. This behavior allows any function to have access to the scope in which it was created, indefinitely. To practically apply this, I immediately invoke a function that returns another function, and because the function I'm returning has access to the internal count variable (because of the closure behavior explained above) this results in a private scope for usage by the resulting function... Not so simple? Let's dilute it down...

A simple one-line closure

//          _______________________Immediately invoked______________________
//         |                                                                |
//         |        Scope retained for use      ___Returned as the____      |
//         |       only by returned function   |    value of func     |     |
//         |             |            |        |                      |     |
//         v             v            v        v                      v     v
var func = (function() { var a = 'val'; return function() { alert(a); }; })();

All variables outside the returned function are available to the returned function, but they are not directly available to the returned function object...

func();  // Alerts "val"
func.a;  // Undefined

Get it? So in our primary example, the count variable is contained within the closure and always available to the event handler, so it retains its state from click to click.

Also, this private variable state is fully accessible, for both readings and assigning to its private scoped variables.

There you go; you're now fully encapsulating this behavior.

Full Blog Post (including jQuery considerations)

7 upvote
  flag
I don't agree with your definition of what a closure is. There's no reason it has to be self-invoking. It's also a bit simplistic (and inaccurate) to say it has to be "returned" (lots of discussion on this in the comments of the top answer to this question) – James Montagne
34 upvote
  flag
@James even if you desagree, his example (and entire post) is one of the best I've seen. While the question is not old and solved for me, it totally deserve a +1. – e-satis
65 upvote
  flag
"I need to know how many times a button has been clicked, and do something on every third click..." THIS got my attention. A use case and the solution showing how a closure is not such a mysterious thing and that alot of us have been writing them but didn't exactly know the official name. – Chris22
upvote
  flag
Nice example because it shows that "count" in the 2nd example retains the value of "count" and not reset to 0 each time the "element" is clicked. Very informative! – Adam
upvote
  flag
+1 for the closure behavior. Can we limit closure behavior to functions in javascript or this concept can also be applied to other structures of the language? – Dziamid
upvote
  flag
The first example already contains a closure. So he is already enclosing the counter in the inner function. The second example just hides it from the global scope adding an extra layer and invokes it. – galileopy
upvote
  flag
@galileopy, it's not clear if the first example uses a closure or not. Normally, global variables don't count as closed over, because they are already accessible everywhere. It's important distinction, because the first example can be translated to a language like C, which doesn't have closures, while the second cannot. – ivant
upvote
  flag
good example since I also usually find myself needed closures within the context of event handlers who need access to the outside scope variables, especially with third party libraries in javascript where it is necessary to provide a function matching the required definition but also need the outside context, viz. angular component context. – Brandon Søren Culley

Okay, talking with a 6-year old child, I would possibly use following associations.

Imagine - you are playing with your little brothers and sisters in the entire house, and you are moving around with your toys and brought some of them into your older brother's room. After a while your brother returned from the school and went to his room, and he locked inside it, so now you could not access toys left there anymore in a direct way. But you could knock the door and ask your brother for that toys. This is called toy's closure; your brother made it up for you, and he is now into outer scope.

Compare with a situation when a door was locked by draft and nobody inside (general function execution), and then some local fire occur and burn down the room (garbage collector:D), and then a new room was build and now you may leave another toys there (new function instance), but never get the same toys which were left in the first room instance.

For an advanced child I would put something like the following. It is not perfect, but it makes you feel about what it is:

function playingInBrothersRoom (withToys) {
  // We closure toys which we played in the brother's room. When he come back and lock the door
  // your brother is supposed to be into the outer [[scope]] object now. Thanks god you could communicate with him.
  var closureToys = withToys || [],
      returnToy, countIt, toy; // Just another closure helpers, for brother's inner use.

  var brotherGivesToyBack = function (toy) {
    // New request. There is not yet closureToys on brother's hand yet. Give him a time.
    returnToy = null;
    if (toy && closureToys.length > 0) { // If we ask for a specific toy, the brother is going to search for it.

      for ( countIt = closureToys.length; countIt; countIt--) {
        if (closureToys[countIt - 1] == toy) {
          returnToy = 'Take your ' + closureToys.splice(countIt - 1, 1) + ', little boy!';
          break;
        }
      }
      returnToy = returnToy || 'Hey, I could not find any ' + toy + ' here. Look for it in another room.';
    }
    else if (closureToys.length > 0) { // Otherwise, just give back everything he has in the room.
      returnToy = 'Behold! ' + closureToys.join(', ') + '.';
      closureToys = [];
    }
    else {
      returnToy = 'Hey, lil shrimp, I gave you everything!';
    }
    console.log(returnToy);
  }
  return brotherGivesToyBack;
}
// You are playing in the house, including the brother's room.
var toys = ['teddybear', 'car', 'jumpingrope'],
    askBrotherForClosuredToy = playingInBrothersRoom(toys);

// The door is locked, and the brother came from the school. You could not cheat and take it out directly.
console.log(askBrotherForClosuredToy.closureToys); // Undefined

// But you could ask your brother politely, to give it back.
askBrotherForClosuredToy('teddybear'); // Hooray, here it is, teddybear
askBrotherForClosuredToy('ball'); // The brother would not be able to find it.
askBrotherForClosuredToy(); // The brother gives you all the rest
askBrotherForClosuredToy(); // Nothing left in there

As you can see, the toys left in the room are still accessible via the brother and no matter if the room is locked. Here is a jsbin to play around with it.

I'd simply point them to the Mozilla Closures page. It's the best, most concise and simple explanation of closure basics and practical usage that I've found. It is highly recommended to anyone learning JavaScript.

And yes, I'd even recommend it to a 6-year old -- if the 6-year old is learning about closures, then it's logical they're ready to comprehend the concise and simple explanation provided in the article.

If you want to explain it to a six-year old child then you must find something very much simpler and NO code.

Just tell the child that he is "open", which says that he is able to have relations with some others, his friends. At some point in time, he has determined friends (we can know the names of his friends), that is a closure. If you take a picture of him and his friends then he is "closed" relatively to his friendship ability. But in general, he is "open". During his whole life he will have many different sets of friends. One of these sets is a closure.

upvote
  flag
I like it, association close friend - closure, nice. Nice mimic to keep picture, not only for child:) Though bit blurry, it sounds a bit as, 'when you will grow up you will understand' I would not like such answers when I was 6 :D, but I like it now – dmi3y

I found very clear chapter 8 section 6, "Closures," of JavaScript: The Definitive Guide by David Flanagan, 6th edition, O'Reilly, 2011. I'll try to paraphrase.

  1. When a function is invoked, a new object is created to hold the local variables for that invocation.

  2. A function's scope depends on its declaration location, not its execution location.

Now, assume an inner function declared within an outer function and referring to variables of that outer function. Further assume the outer function returns the inner function, as a function. Now there is an external reference to whatever values were in the inner function's scope (which, by our assumptions, includes values from the outer function).

JavaScript will preserve those values, as they have remained in scope of the current execution thanks to being passed out of the completed outer function. All functions are closures, but the closures of interest are the inner functions which, in our assumed scenario, preserve outer function values within their "enclosure" (I hope I'm using language correctly here) when they (the inner functions) are returned from outer functions. I know this doesn't meet the six-year-old requirement, but hopefully it is still helpful.

A function is executed in the scope of the object/function in which it is defined. The said function can access the variables defined in the object/function where it has been defined while it is executing.

And just take it literally.... as the code is written :P

For a six-year-old?

You and your family live in the mythical town of Ann Ville. You have a friend who lives next door, so you call them and ask them to come out and play. You dial:

000001 (jamiesHouse)

After a month, you and your family move out of Ann Ville to the next town, but you and your friend still keep in touch, so now you have to dial the area code for the town that your friend lives in, before dialling their 'proper' number:

001 000001 (annVille.jamiesHouse)

A year after that, your parents move to a whole new country, but you and your friend still keep in touch, so after bugging your parents to let you make international rate calls, you now dial:

01 001 000001 (myOldCountry.annVille.jamiesHouse)

Strangely though, after moving to your new country, you and your family just so happen to move to a new town called Ann Ville... and you just so happen to make friends with some new person called Jamie... You give them a call...

000001 (jamiesHouse)

Spooky...

So spooky in fact, that you tell Jamie from your old country about it... You have a good laugh about it. So one day, you and your family take a holiday back to the old country. You visit your old town (Ann Ville), and go to visit Jamie...

  • "Really? Another Jamie? In Ann Ville? In your new country!!?"
  • "Yeah... Let's call them..."

02 001 000001 (myNewCountry.annVille.jamiesHouse)

Opinions?

What's more, I have a load of questions about the patience of a modern six-year-old...

8 upvote
  flag
so.. what's the clousure here? jamiesHouse? I don't get it – vivoconunxino
upvote
  flag
No. 'annVille' is the 'closure'. If you live in annVille, you can call '.jamiesHouse' directly. If you live outside of annVille, you'll have to call 'annVille.jamiesHouse' (assuming that I've chosen to expose annVille's population to the world, of course). Bear in mind this is intended to be a primer for a 6 y/o kid, with absolutely no code involved. A thorough explanation would obviously need more detail. – Charlie

An answer for a six-year-old (assuming he knows what a function is and what a variable is, and what data is):

Functions can return data. One kind of data you can return from a function is another function. When that new function gets returned, all the variables and arguments used in the function that created it don't go away. Instead, that parent function "closes." In other words, nothing can look inside of it and see the variables it used except for the function it returned. That new function has a special ability to look back inside the function that created it and see the data inside of it.

function the_closure() {
  var x = 4;
  return function () {
    return x; // Here, we look back inside the_closure for the value of x
  }
}

var myFn = the_closure();
myFn(); //=> 4

Another really simple way to explain it is in terms of scope:

Any time you create a smaller scope inside of a larger scope, the smaller scope will always be able to see what is in the larger scope.

upvote
  flag
Seems that closure is equivalent to classes and inner classes in O.O. – ComeIn

I'm sure, Einstein didn't say it with a direct expectation for us to pick any esoteric brainstormer thing and run over six-year-olds with futile attempts to get those 'crazy' (and what is even worse for them-boring) things to their childish minds :) If I were six years old I wouldn't like to have such parents or wouldn't make friendship with such boring philanthropists, sorry :)

Anyway, for babies, closure is simply a hug, I guess, whatever way you try to explain :) And when you hug a friend of yours then you both kind of share anything you guys have at the moment. It's a rite of passage, once you've hugged somebody you're showing her trust and willingness to let her do with you a lot of things you don't allow and would hide from others. It's an act of friendship :).

I really don't know how to explain it to 5-6 years old babies. I neither think they will appreciate any JavaScript code snippets like:

function Baby(){
    this.iTrustYou = true;
}

Baby.prototype.hug = function (baby) {
    var smiles = 0;

    if (baby.iTrustYou) {
        return function() {
            smiles++;
            alert(smiles);
        };
    }
};

var
   arman = new Baby("Arman"),
   morgan = new Baby("Morgana");

var hug = arman.hug(morgan);
hug();
hug();

For children only:

Closure is hug

Bug is fly

KISS is smooch! :)

OK, 6-year-old closures fan. Do you want to hear the simplest example of closure?

Let's imagine the next situation: a driver is sitting in a car. That car is inside a plane. Plane is in the airport. The ability of driver to access things outside his car, but inside the plane, even if that plane leaves an airport, is a closure. That's it. When you turn 27, look at the more detailed explanation or at the example below.

Here is how I can convert my plane story into the code.

var plane = function (defaultAirport) {

    var lastAirportLeft = defaultAirport;

    var car = {
        driver: {
            startAccessPlaneInfo: function () {
                setInterval(function () {
                    console.log("Last airport was " + lastAirportLeft);
                }, 2000);
            }
        }
    };
    car.driver.startAccessPlaneInfo();

    return {
        leaveTheAirport: function (airPortName) {
            lastAirportLeft = airPortName;
        }
    }
}("Boryspil International Airport");

plane.leaveTheAirport("John F. Kennedy");
23 upvote
  flag
Well played and answers the original poster. I think this is the best answer. I was going to use luggage in a similar way: imagine you go to grandma's house and you pack your nintendo DS case with game cards inside your case, but then pack the case inside your backpack and also put game cards in your backpack pockets, and THEN you put the whole thing in a big suitcase with more game cards in the pockets of the suitcase. When you get to Grandma's house, you can play any game on your DS as long as all the outside cases are open. or something to that effect. – slartibartfast

I tend to learn better by GOOD/BAD comparisons. I like to see working code followed by non-working code that someone is likely to encounter. I put together a jsFiddle that does a comparison and tries to boil down the differences to the simplest explanations I could come up with.

Closures done right:

console.log('CLOSURES DONE RIGHT');

var arr = [];

function createClosure(n) {
    return function () {
        return 'n = ' + n;
    }
}

for (var index = 0; index < 10; index++) {
    arr[index] = createClosure(index);
}

for (var index in arr) {
    console.log(arr[index]());
}
  • In the above code createClosure(n) is invoked in every iteration of the loop. Note that I named the variable n to highlight that it is a new variable created in a new function scope and is not the same variable as index which is bound to the outer scope.

  • This creates a new scope and n is bound to that scope; this means we have 10 separate scopes, one for each iteration.

  • createClosure(n) returns a function that returns the n within that scope.

  • Within each scope n is bound to whatever value it had when createClosure(n) was invoked so the nested function that gets returned will always return the value of n that it had when createClosure(n) was invoked.

Closures done wrong:

console.log('CLOSURES DONE WRONG');

function createClosureArray() {
    var badArr = [];

    for (var index = 0; index < 10; index++) {
        badArr[index] = function () {
            return 'n = ' + index;
        };
    }
    return badArr;
}

var badArr = createClosureArray();

for (var index in badArr) {
    console.log(badArr[index]());
}
  • In the above code the loop was moved within the createClosureArray() function and the function now just returns the completed array, which at first glance seems more intuitive.

  • What might not be obvious is that since createClosureArray() is only invoked once only one scope is created for this function instead of one for every iteration of the loop.

  • Within this function a variable named index is defined. The loop runs and adds functions to the array that return index. Note that index is defined within the createClosureArray function which only ever gets invoked one time.

  • Because there was only one scope within the createClosureArray() function, index is only bound to a value within that scope. In other words, each time the loop changes the value of index, it changes it for everything that references it within that scope.

  • All of the functions added to the array return the SAME index variable from the parent scope where it was defined instead of 10 different ones from 10 different scopes like the first example. The end result is that all 10 functions return the same variable from the same scope.

  • After the loop finished and index was done being modified the end value was 10, therefore every function added to the array returns the value of the single index variable which is now set to 10.

Result

CLOSURES DONE RIGHT
n = 0
n = 1
n = 2
n = 3
n = 4
n = 5
n = 6
n = 7
n = 8
n = 9

CLOSURES DONE WRONG
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10

1 upvote
  flag
Nice addition, thanks. Just to make it more clear one can imagine how the "bad" array is created in the "bad" loop with each iteration: 1st iteration: [function () {return 'n = ' + 0;}] 2nd iteration: [(function () {return 'n = ' + 1;}),(function () {return 'n = ' + 1;})] 3rd iteration: [(function () {return 'n = ' + 2;}),(function () {return 'n = ' + 2;}),(function () {return 'n = ' + 2;})] etc. So, each time when the index value changes it is reflected in all functions already added to the array. – Alex Alexeev
1 upvote
  flag
Best working definition here! – KK.
upvote
  flag
Using let for var fixes the difference. – Rupam Datta

Given the following function

function person(name, age){

    var name = name;
    var age = age;

    function introduce(){
        alert("My name is "+name+", and I'm "+age);
    }

    return introduce;
}

var a = person("Jack",12);
var b = person("Matt",14);

Everytime the function person is called a new closure is created. While variables a and b have the same introduce function, it is linked to different closures. And that closure will still exist even after the function person finishes execution.

Enter image description here

a(); //My name is Jack, and I'm 12
b(); //My name is Matt, and I'm 14

An abstract closures could be represented to something like this:

closure a = {
    name: "Jack",
    age: 12,
    call: function introduce(){
        alert("My name is "+name+", and I'm "+age);
    }
}

closure b = {
    name: "Matt",
    age: 14,
    call: function introduce(){
        alert("My name is "+name+", and I'm "+age);
    }
}

Assuming you know how a class in another language work, I will make an analogy.

Think like

  • JavaScript function as a constructor
  • local variables as instance properties
  • these properties are private
  • inner functions as instance methods

Everytime a function is called

  • A new object containing all local variables will be created.
  • Methods of this object have access to "properties" of that instance object.

Considering the question is about explaining it simply as if to a 6-year-old, my answer would be:

"When you declare a function in JavaScript it has forever access to all the variables and functions that were available in the line before that function declaration. The function and all the outer variables and functions that it has access to is what we call a closure."

2 upvote
  flag
It is not necessary to be the line before, you can declare a var or function in the same scope where you are declaring the function after that function declaration and it will see it too. JavaScript it is not a line interpreter. – Juan Garcia
1 upvote
  flag
I believe it would be easier for a 6-year old to visualize through the example instead of having to understand how the concept of scope and the interpreter come into play. – Raul Martins

Closures are simple:

The following simple example covers all the main points of JavaScript closures.*  

Here is a factory that produces calculators that can add and multiply:

function make_calculator() {
  var n = 0; // this calculator stores a single number n
  return {
    add: function(a) {
      n += a;
      return n;
    },
    multiply: function(a) {
      n *= a;
      return n;
    }
  };
}

first_calculator = make_calculator();
second_calculator = make_calculator();

first_calculator.add(3); // returns 3
second_calculator.add(400); // returns 400

first_calculator.multiply(11); // returns 33
second_calculator.multiply(10); // returns 4000

The key point: Each call to make_calculator creates a new local variable n, which continues to be usable by that calculator's add and multiply functions long after make_calculator returns.

If you are familiar with stack frames, these calculators seem strange: How can they keep accessing n after make_calculator returns? The answer is to imagine that JavaScript doesn't use "stack frames", but instead uses "heap frames", which can persist after the function call that made them returns.

Inner functions like add and multiply, which access variables declared in an outer function**, are called closures.

That is pretty much all there is to closures.



* For example, it covers all the points in the "Closures for Dummies" article given in another answer, except example 6, which simply shows that variables can be used before they are declared, a nice fact to know but completely unrelated to closures. It also covers all the points in the accepted answer, except for the points (1) that functions copy their arguments into local variables (the named function arguments), and (2) that copying numbers creates a new number, but copying an object reference gives you another reference to the same object. These are also good to know but again completely unrelated to closures. It is also very similar to the example in this answer but a bit shorter and less abstract. It does not cover the point of this answer or this comment, which is that JavaScript makes it difficult to plug the current value of a loop variable into your inner function: The "plugging in" step can only be done with a helper function that encloses your inner function and is invoked on each loop iteration. (Strictly speaking, the inner function accesses the helper function's copy of the variable, rather than having anything plugged in.) Again, very useful when creating closures, but not part of what a closure is or how it works. There is additional confusion due to closures working differently in functional languages like ML, where variables are bound to values rather than to storage space, providing a constant stream of people who understand closures in a way (namely the "plugging in" way) that is simply incorrect for JavaScript, where variables are always bound to storage space, and never to values.

** Any outer function, if several are nested, or even in the global context, as this answer points out clearly.

upvote
  flag
What would happen if you called : second_calculator = first_calculator(); instead of second_calculator = make_calculator(); ? Should be the same, right? – Ronen Festinger
3 upvote
  flag
@Ronen: Since first_calculator is an object (not a function) you should not use parentheses in second_calculator = first_calculator;, since it is an assignment, not a function call. To answer your question, there would then only be one call to make_calculator, so only one calculator would get made, and the variables first_calculator and second_calculator would both refer to the same calculator, so the answers would be 3, 403, 4433, 44330. – Matt

A closure is basically creating two things : - a function - a private scope that only that function can access

It is like putting some coating around a function.

So to a 6-years-old, it could be explained by giving an analogy. Let's say I build a robot. That robot can do many things. Among those things, I programmed it to count the number of birds he sees in the sky. Each time he has seen 25 birds, he should tell me how many birds he has seen since the beginning.

I don't know how many birds he has seen unless he has told me. Only he knows. That's the private scope. That's basically the robot's memory. Let's say I gave him 4 GB.

Telling me how many birds he has seen is the returned function. I also created that.

That analogy is a bit sucky, but someone could improve it I guess.

The word closure simply refers to being able to access objects (six-year-old: things) that are closed (six-year-old: private) within a function (six-year-old: box). Even if the function (six-year-old: box) is out of scope (six-year-old: sent far away).

The more I think about closure the more I see it as a 2-step process: init - action

init: pass first what's needed...
action: in order to achieve something for later execution.

To a 6-year old, I'd emphasize on the practical aspect of closure:

Daddy: Listen. Could you bring mum some milk (2).
Tom: No problem.
Daddy: Take a look at the map that Daddy has just made: mum is there and daddy is here.
Daddy: But get ready first. And bring the map with you (1), it may come in handy
Daddy: Then off you go (3). Ok?
Tom: A piece of cake!

Example: Bring some milk to mum (=action). First get ready and bring the map (=init).

function getReady(map) {
    var cleverBoy = 'I examine the ' + map;
    return function(what, who) {
        return 'I bring ' + what + ' to ' + who + 'because + ' cleverBoy; //I can access the map
    }
}
var offYouGo = getReady('daddy-map');
offYouGo('milk', 'mum');

Because if you bring with you a very important piece of information (the map), you're knowledgeable enough to execute other similar actions:

offYouGo('potatoes', 'great mum');

To a developer I'd make a parallel between closures and OOP. The init phase is similar to passing arguments to a constructor in a traditional OO language; the action phase is ultimately the method you call to achieve what you want. And the method has access these init arguments using a mechanism called closure.

See my another answer illustrating the parallelism between OO and closures:

How to "properly" create a custom object in JavaScript?

1 upvote
  flag
The "parallel" reference was quite useful for me (given my OOP background). For balance, it also helps if one also reads this: "Closures And Objects Are Equivalent" buff.ly/1gpPIBY – lifebalance
1 upvote
  flag
Mozilla agrees: "you can use a closure anywhere that you might normally use an object with only a single method." developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – Jon Coombs

How I'd explain it to a six-year-old:

You know how grown-ups can own a house, and they call it home? When a mom has a child, the child doesn't really own anything, right? But its parents own a house, so whenever someone asks the child "Where's your home?", he/she can answer "that house!", and point to the house of its parents. A "Closure" is the ability of the child to always (even if abroad) be able to say it has a home, even though it's really the parent's who own the house.

The simplest, shortest, most-easy-to-understand answer:

A closure is a block of code where each line can reference the same set of variables with the same variable names.

If "this" means something different than it does somewhere else, then you know it is two different closures.

If you understand it well you can explain it simple. And the simplest way is abstracting it from the context. Code aside, even programming aside. A metaphor example will do it better.

Let's imagine that a function is a room whose walls are of glass, but they are special glass, like the ones in an interrogation room. From outside they are opaque, from inside they are transparent. It can be rooms inside other rooms, and the only way of contact is a phone.

If you call from the outside, you don't know what is in it, but you know that the people inside will do a task if you give them certain information. They can see outside, so they can ask you for stuff that are outside and make changes to that stuff, but you can't change what it is inside from the outside, you don't even see (know) what it is inside. The people inside that room you are calling see what it is outside, but not what it is inside the rooms in that room, so they interact with them the way you are doing from outside. The people inside the most inner rooms can see many things, but the people of the most outer room don't even know about the most inner rooms' existence.

For each call to an inner room, the people in that room keeps a record of the information about that specific call, and they are so good doing that that they never mistake one call stuff with other call stuff.

Rooms are functions, visibility is scope, people doing task is statements, stuff are objects, phone calls are function calls, phone call information is arguments, call records are scope instances, the most outer room is the global object.

Even though many beautiful definitions of JavaScript closures exists on the Internet, I am trying to start explaining my six-year-old friend with my favourite definitions of closure which helped me to understand the closure much better.

What is a Closure?

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

A closure is the local variables for a function - kept alive after the function has returned.

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created in.

Closures are an extension of the concept of scope. With closures, functions have access to variables that were available in the scope where the function was created.

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!)

Languages such as Java provide the ability to declare methods private, meaning that they can only be called by other methods in the same class. JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures.

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

Closures are an abstraction mechanism that allow you to separate concerns very cleanly.

Uses of Closures:

Closures are useful in hiding the implementation of functionality while still revealing the interface.

You can emulate the encapsulation concept in JavaScript using closures.

Closures are used extensively in jQuery and Node.js.

While object literals are certainly easy to create and convenient for storing data, closures are often a better choice for creating static singleton namespaces in a large web application.

Example of Closures:

Assuming my 6-year-old friend get to know addition very recently in his primary school, I felt this example of adding the two numbers would be the simplest and apt for the six-year-old to learn the closure.

Example 1: Closure is achieved here by returning a function.

function makeAdder(x) {
    return function(y) {
        return x + y;
    };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

Example 2: Closure is achieved here by returning an object literal.

function makeAdder(x) {
    return {
        add: function(y){
            return x + y;
        }
    }
}

var add5 = makeAdder(5);
console.log(add5.add(2));//7

var add10 = makeAdder(10);
console.log(add10.add(2));//12

Example 3: Closures in jQuery

$(function(){
    var name="Closure is easy";
    $('div').click(function(){
        $('p').text(name);
    });
});

Useful Links:

Thanks to the above links which helps me to understand and explain closure better.

I have read all of these before in the past, and they are all very informative. Some come very close to getting the simple explanation and then get complex or remain abstract, defeating the purpose and failing to show a very simple real world use.

Though combing through all the examples and explanations you get a good idea of what closures are and aren't via comments and code, I was still unsatisfied with a very simple illustration that helped me get a closures usefulness without getting so complex. My wife wants to learn coding and I figured I needed to be able to show here not only what, but why, and and how.

I am not sure a six year old will get this, but I think it might be a little closer to demonstrating a simple case in a real world way that might acually be useful and that is easily understandable.

One of the best (or closest to simplest) is the retelling of Morris' Closures for Dummies example.

Taking the "SayHi2Bob" concept just one step further demonstrates the two basic things you can glean from reading all the answers:

  1. Closures have access to the containing function's variables.
  2. Closures persist in their own memory space (and thus are useful for all kinds of oop-y instantiation stuff)

Proving and demonstrating this to myself, I made a little fiddle:

http://jsfiddle.net/9ZMyr/2/

function sayHello(name) {
  var text = 'Hello ' + name; // Local variable
  console.log(text);
  var sayAlert = function () {
      alert(text);
  }
  return sayAlert;
}

sayHello(); 
/* This will write 'Hello undefined' to the console (in Chrome anyway), 
but will not alert though since it returns a function handle to nothing). 
Since no handle or reference is created, I imagine a good js engine would 
destroy/dispose of the internal sayAlert function once it completes. */

// Create a handle/reference/instance of sayHello() using the name 'Bob'
sayHelloBob = sayHello('Bob');
sayHelloBob();

// Create another handle or reference to sayHello with a different name
sayHelloGerry = sayHello('Gerry');
sayHelloGerry();

/* Now calling them again demonstrates that each handle or reference contains its own 
unique local variable memory space. They remain in memory 'forever' 
(or until your computer/browser explode) */
sayHelloBob();
sayHelloGerry();

This demonstrates both of the basic concepts you should get about closures.

In simple terms to explain the why this is useful, I have a base function to which I can make references or handles that contain unique data which persists within that memory reference. I don't have to rewrite the function for each time I want to say someone's name. I have encapsulated that routine and made it reusable.

To me this leads to at least the basic concepts of constructors, oop practices, singletons vs instantiated instances with their own data, etc. etc.

If you start a neophyte with this, then you can move on to more complex object property/member based calls, and hopefully the concepts carry.

A closure is created when the inner function is somehow made available to any scope outside the outer function.

Example:

var outer = function(params){ //Outer function defines a variable called params
    var inner = function(){ // Inner function has access to the params variable of the outer function
        return params;
    }
    return inner; //Return inner function exposing it to outer scope
},
myFunc = outer("myParams");
myFunc(); //Returns "myParams"

Closure is when a function is closed in a way that it was defined in a namespace which is immutable by the time the function is called.

In JavaScript, it happens when you:

  • Define one function inside the other function
  • The inner function is called after the outer function returned
// 'name' is resolved in the namespace created for one invocation of bindMessage
// the processor cannot enter this namespace by the time displayMessage is called
function bindMessage(name, div) {

    function displayMessage() {
        alert('This is ' + name);
    }

    $(div).click(displayMessage);
}

I think it is valuable to take a step back, and examine a more general notion of a "closure" -- the so-called "join operator".

In mathematics, a "join" operator is a function on a partially ordered set which returns the smallest object greater than or equal to its arguments. In symbols, join [a,b] = d such that d >= a and d >= b, but there does not exist an e such that d > e >= a or d > e >= b.

So the join gives you the smallest thing "bigger" than the parts.

Now, note that JavaScript scopes are a partially ordered structure. So that there is a sensible notion of a join. In particular, a join of scopes is the smallest scope bigger than the original scopes. That scope is called the closure.

So a closure for the variables a, b, c is the smallest scope (in the lattice of scopes for your program!) that brings a, b, and c into scope.

A closure is a block of code which meets three criteria:

  • It can be passed around as a value and

  • executed on demand by anyone who has that value, at which time

  • it can refer to variables from the context in which it was created (that is, it is closed with respect to variable access, in the mathematical sense of the word "closed").

(The word "closure" actually has an imprecise meaning, and some people don't think that criterion #1 is part of the definition. I think it is.)

Closures are a mainstay of functional languages, but they are present in many other languages as well (for example, Java's anonymous inner classes). You can do cool stuff with them: they allow deferred execution and some elegant tricks of style.

By: Paul Cantrell, @ http://innig.net/software/ruby/closures-in-ruby

Imagine there is a very large park in your town where you see a magician called Mr. Coder starting baseball games in different corners of the park using his magic wand, called JavaScript.

Naturally each baseball game has the exact same rules and each game has its own score board.

Naturally, the scores of one baseball game are completely separate from the other games.

A closure is the special way Mr.Coder keeps the scoring of all his magical baseball games separate.

Here is a simple real-time scenario. Just read it through, and you will understand how we have used closure here (see how seat number is changing).

All other examples explained previously are also very good to understand the concept.

function movieBooking(movieName) {
    var bookedSeatCount = 0;
    return function(name) {
        ++bookedSeatCount ;
        alert( name + " - " + movieName + ", Seat - " + bookedSeatCount )
    };
};

var MI1 = movieBooking("Mission Impossible 1 ");
var MI2 = movieBooking("Mission Impossible 2 ");

MI1("Mayur");
// alert
// Mayur - Mission Impossible 1, Seat - 1

MI1("Raju");
// alert
// Raju - Mission Impossible 1, Seat - 2

MI2("Priyanka");
// alert
// Raja - Mission Impossible 2, Seat - 1

As a father of a 6-year-old, currently teaching young children (and a relative novice to coding with no formal education so corrections will be required), I think the lesson would stick best through hands-on play. If the 6-year-old is ready to understand what a closure is, then they are old enough to have a go themselves. I'd suggest pasting the code into jsfiddle.net, explaining a bit, and leaving them alone to concoct a unique song. The explanatory text below is probably more appropriate for a 10 year old.

function sing(person) {

    var firstPart = "There was " + person + " who swallowed ";

    var fly = function() {
        var creature = "a fly";
        var result = "Perhaps she'll die";
        alert(firstPart + creature + "\n" + result);
    };

    var spider = function() {
        var creature = "a spider";
        var result = "that wiggled and jiggled and tickled inside her";
        alert(firstPart + creature + "\n" + result);
    };

    var bird = function() {
        var creature = "a bird";
        var result = "How absurd!";
        alert(firstPart + creature + "\n" + result);
    };

    var cat = function() {
        var creature = "a cat";
        var result = "Imagine That!";
        alert(firstPart + creature + "\n" + result);
    };

    fly();
    spider();
    bird();
    cat();
}

var person="an old lady";

sing(person);

INSTRUCTIONS

DATA: Data is a collection of facts. It can be numbers, words, measurements, observations or even just descriptions of things. You can't touch it, smell it or taste it. You can write it down, speak it and hear it. You could use it to create touch smell and taste using a computer. It can be made useful by a computer using code.

CODE: All the writing above is called code. It is written in JavaScript.

JAVASCRIPT: JavaScript is a language. Like English or French or Chinese are languages. There are lots of languages that are understood by computers and other electronic processors. For JavaScript to be understood by a computer it needs an interpreter. Imagine if a teacher who only speaks Russian comes to teach your class at school. When the teacher says "все садятся", the class would not understand. But luckily you have a Russian pupil in your class who tells everyone this means "everybody sit down" - so you all do. The class is like a computer and the Russian pupil is the interpreter. For JavaScript the most common interpreter is called a browser.

BROWSER: When you connect to the Internet on a computer, tablet or phone to visit a website, you use a browser. Examples you may know are Internet Explorer, Chrome, Firefox and Safari. The browser can understand JavaScript and tell the computer what it needs to do. The JavaScript instructions are called functions.

FUNCTION: A function in JavaScript is like a factory. It might be a little factory with only one machine inside. Or it might contain many other little factories, each with many machines doing different jobs. In a real life clothes factory you might have reams of cloth and bobbins of thread going in and T-shirts and jeans coming out. Our JavaScript factory only processes data, it can't sew, drill a hole or melt metal. In our JavaScript factory data goes in and data comes out.

All this data stuff sounds a bit boring, but it is really very cool; we might have a function that tells a robot what to make for dinner. Let's say I invite you and your friend to my house. You like chicken legs best, I like sausages, your friend always wants what you want and my friend does not eat meat.

I haven't got time to go shopping, so the function needs to know what we have in the fridge to make decisions. Each ingredient has a different cooking time and we want everything to be served hot by the robot at the same time. We need to provide the function with the data about what we like, the function could 'talk' to the fridge, and the function could control the robot.

A function normally has a name, parentheses and braces. Like this:

function cookMeal() {  /*  STUFF INSIDE THE FUNCTION  */  }

Note that /*...*/ and // stop code being read by the browser.

NAME: You can call a function just about whatever word you want. The example "cookMeal" is typical in joining two words together and giving the second one a capital letter at the beginning - but this is not necessary. It can't have a space in it, and it can't be a number on its own.

PARENTHESES: "Parentheses" or () are the letter box on the JavaScript function factory's door or a post box in the street for sending packets of information to the factory. Sometimes the postbox might be marked for example cookMeal(you, me, yourFriend, myFriend, fridge, dinnerTime), in which case you know what data you have to give it.

BRACES: "Braces" which look like this {} are the tinted windows of our factory. From inside the factory you can see out, but from the outside you can't see in.

THE LONG CODE EXAMPLE ABOVE

Our code begins with the word function, so we know that it is one! Then the name of the function sing - that's my own description of what the function is about. Then parentheses (). The parentheses are always there for a function. Sometimes they are empty, and sometimes they have something in. This one has a word in: (person). After this there is a brace like this { . This marks the start of the function sing(). It has a partner which marks the end of sing() like this }

function sing(person) {  /* STUFF INSIDE THE FUNCTION */  }

So this function might have something to do with singing, and might need some data about a person. It has instructions inside to do something with that data.

Now, after the function sing(), near the end of the code is the line

var person="an old lady";

VARIABLE: The letters var stand for "variable". A variable is like an envelope. On the outside this envelope is marked "person". On the inside it contains a slip of paper with the information our function needs, some letters and spaces joined together like a piece of string (it's called a string) that make a phrase reading "an old lady". Our envelope could contain other kinds of things like numbers (called integers), instructions (called functions), lists (called arrays). Because this variable is written outside of all the braces {}, and because you can see out through the tinted windows when you are inside the braces, this variable can be seen from anywhere in the code. We call this a 'global variable'.

GLOBAL VARIABLE: person is a global variable, meaning that if you change its value from "an old lady" to "a young man", the person will keep being a young man until you decide to change it again and that any other function in the code can see that it's a young man. Press the F12 button or look at the Options settings to open the developer console of a browser and type "person" to see what this value is. Type person="a young man" to change it and then type "person" again to see that it has changed.

After this we have the line

sing(person);

This line is calling the function, as if it were calling a dog

"Come on sing, Come and get person!"

When the browser has loaded the JavaScript code an reached this line, it will start the function. I put the line at the end to make sure that the browser has all the information it needs to run it.

Functions define actions - the main function is about singing. It contains a variable called firstPart which applies to the singing about the person that applies to each of the verses of the song: "There was " + person + " who swallowed". If you type firstPart into the console, you won't get an answer because the variable is locked up in a function - the browser can't see inside the tinted windows of the braces.

CLOSURES: The closures are the smaller functions that are inside the big sing() function. The little factories inside the big factory. They each have their own braces which mean that the variables inside them can't be seen from the outside. That's why the names of the variables (creature and result) can be repeated in the closures but with different values. If you type these variable names in the console window, you won't get its value because it's hidden by two layers of tinted windows.

The closures all know what the sing() function's variable called firstPart is, because they can see out from their tinted windows.

After the closures come the lines

fly();
spider();
bird();
cat();

The sing() function will call each of these functions in the order they are given. Then the sing() function's work will be done.

In JavaScript closures are awesome, where variables or arguments are available to inner functions, and they will be alive even after the outer function has returned.

  function getFullName(a, b) {
  return a + b;
}

function makeFullName(fn) {

  return function(firstName) {

    return function(secondName) {

      return fn(firstName, secondName);
    }
  }
}

makeFullName(getFullName)("stack")("overflow"); // Stackoverflow

Maybe you should consider an object-oriented structure instead of inner functions. For example:

var calculate = {
    number: 0,
    init: function (num) {
        this.number = num;
    },
    add: function (val) {
        this.number += val;
    },
    rem: function (val) {
        this.number -= val;
    }
};

And read the result from the calculate.number variable, who needs "return" anyway.

1 upvote
  flag
I don't believe this is even a closure. – John Gibb
1 upvote
  flag
@JohnGibb I believe creates a closure (the functions can access the calculate object by name) but then doesn't use the closure whatsoever. – slicedtoad
upvote
  flag
As I commented under floribon's answer, function+closure does resemble method+object in some ways. I think this answer would be much more useful if it provided the idiomatic JS equivalent to the OO structure shown (but probably without rem). The outer function would do the init--storing number in the closure--and the inner function would add to number. – Jon Coombs
upvote
  flag
Mozilla agrees: "you can use a closure anywhere that you might normally use an object with only a single method." developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – Jon Coombs

I do not understand why the answers are so complex here.

Here is a closure:

var a = 42;

function b() { return a; }

Yes. You probably use that many times a day.


There is no reason to believe closures are a complex design hack to address specific problems. No, closures are just about using a variable that comes from a higher scope from the perspective of where the function was declared (not run).

Now what it allows you to do can be more spectacular, see other answers.

4 upvote
  flag
This answer doesn't seem likely to help unconfuse people. A rough equivalent in a traditional programming language might be to create b() as a method on an object that also has a private constant or property a. To my mind, the surprise is that the JS scope object effectively provides a as a property rather than a constant. And you'll only notice that important behavior if you modify it, as in return a++; – Jon Coombs
upvote
  flag
Exactly what Jon said. Before I finally grokked closures I had a hard time finding practical examples. Yes, floribon created a closure, but to uneducated me this would have taught me absolutely nothing. – Chev
3 upvote
  flag
This does not define what a closure is -- it is merely an example that uses one. And it doesn't address the nuance of what happens when the scope ends; I don't think anyone had a question about lexical scoping when all the scopes are still around, and especially in the case of a global variable. – Gerard ONeill

Perhaps a little beyond all but the most precocious of six-year-olds, but a few examples that helped make the concept of closure in JavaScript click for me.

A closure is a function that has access to another function's scope (its variables and functions). The easiest way to create a closure is with a function within a function; the reason being that in JavaScript a function always has access to its containing function’s scope.

function outerFunction() {
    var outerVar = "monkey";
    
    function innerFunction() {
        alert(outerVar);
    }
    
    innerFunction();
}

outerFunction();

ALERT: monkey

In the above example, outerFunction is called which in turn calls innerFunction. Note how outerVar is available to innerFunction, evidenced by its correctly alerting the value of outerVar.

Now consider the following:

function outerFunction() {
    var outerVar = "monkey";
    
    function innerFunction() {
        return outerVar;
    }
    
    return innerFunction;
}

var referenceToInnerFunction = outerFunction();
alert(referenceToInnerFunction());

ALERT: monkey

referenceToInnerFunction is set to outerFunction(), which simply returns a reference to innerFunction. When referenceToInnerFunction is called, it returns outerVar. Again, as above, this demonstrates that innerFunction has access to outerVar, a variable of outerFunction. Furthermore, it is interesting to note that it retains this access even after outerFunction has finished executing.

And here is where things get really interesting. If we were to get rid of outerFunction, say set it to null, you might think that referenceToInnerFunction would loose its access to the value of outerVar. But this is not the case.

function outerFunction() {
    var outerVar = "monkey";
    
    function innerFunction() {
        return outerVar;
    }
    
    return innerFunction;
}

var referenceToInnerFunction = outerFunction();
alert(referenceToInnerFunction());

outerFunction = null;
alert(referenceToInnerFunction());

ALERT: monkey ALERT: monkey

But how is this so? How can referenceToInnerFunction still know the value of outerVar now that outerFunction has been set to null?

The reason that referenceToInnerFunction can still access the value of outerVar is because when the closure was first created by placing innerFunction inside of outerFunction, innerFunction added a reference to outerFunction’s scope (its variables and functions) to its scope chain. What this means is that innerFunction has a pointer or reference to all of outerFunction’s variables, including outerVar. So even when outerFunction has finished executing, or even if it is deleted or set to null, the variables in its scope, like outerVar, stick around in memory because of the outstanding reference to them on the part of the innerFunction that has been returned to referenceToInnerFunction. To truly release outerVar and the rest of outerFunction’s variables from memory you would have to get rid of this outstanding reference to them, say by setting referenceToInnerFunction to null as well.

//////////

Two other things about closures to note. First, the closure will always have access to the last values of its containing function.

function outerFunction() {
    var outerVar = "monkey";
    
    function innerFunction() {
        alert(outerVar);
    }
    
    outerVar = "gorilla";

    innerFunction();
}

outerFunction();

ALERT: gorilla

Second, when a closure is created, it retains a reference to all of its enclosing function’s variables and functions; it doesn’t get to pick and choose. And but so, closures should be used sparingly, or at least carefully, as they can be memory intensive; a lot of variables can be kept in memory long after a containing function has finished executing.

(I am not taking the 6-years-old thing into account.)

In a language like JavaScript, where you can pass functions as parameters to other functions (languages where functions are first class citizens), you will often find yourself doing something like:

var name = 'Rafael';

var sayName = function() {
  console.log(name);
};

You see, sayName doesn't have the definition for the name variable, but it does use the value of name that was defined outside of sayName (in a parent scope).

Let's say you pass sayName as a parameter to another function, that will call sayName as a callback:

functionThatTakesACallback(sayName);

Note that:

  1. sayName will be called from inside functionThatTakesACallback (assume that, since I haven't implemented functionThatTakesACallback in this example).
  2. When sayName is called, it will log the value of the name variable.
  3. functionThatTakesACallback doesn't define a name variable (well, it could, but it wouldn't matter, so assume it doesn't).

So we have sayName being called inside functionThatTakesACallback and referring to a name variable that is not defined inside functionThatTakesACallback.

What happens then? A ReferenceError: name is not defined?

No! The value of name is captured inside a closure. You can think of this closure as context associated to a function, that holds the values that were available where that function was defined.

So: Even though name is not in scope where the function sayName will be called (inside functionThatTakesACallback), sayName can access the value for name that is captured in the closure associated with sayName.

Here's the most Zen answer I can give:

What would you expect this code to do? Tell me in a comment before you run it. I'm curious!

function foo() {
  var i = 1;
  return function() {
    console.log(i++);
  }
}

var bar = foo();
bar();
bar();
bar();

var baz = foo();
baz();
baz();
baz();

Now open the console in your browser (Ctrl + Shift + I or F12, hopefully) and paste the code in and hit Enter.

If this code printed what you expect (JavaScript newbies - ignore the "undefined" at the end), then you already have wordless understanding. In words, the variable i is part of the inner function instance's closure.

I put it this way because, once I understood that this code is putting instances of foo()'s inner function in bar and baz and then calling them via those variables, nothing else surprised me.

But if I'm wrong and the console output surprised you, let me know!

upvote
  flag
1 2 3 1 2 3. Yup. But in a more traditional language I'd expect syntax errors or else 1 1 1 1 1 1. – Jon Coombs
upvote
  flag
FWIW, to get the 1 1 1 1 1 1 effect in JS, you can put var j = i; inside the inner function and then use console.log(j++); instead. Useless, but more familiar to some of us. So in this scenario, I do think closures are more intuitive to the uninitiated than to many trained programmers. – Jon Coombs
upvote
  flag
@JonCoombs interesting, I see. So you were expecting that every time the inner function is called, var i = 1 gets copied into its scope anew? – Andy
upvote
  flag
@JonCoombs it's possible that everything was intuitive for me since I was already well-versed in Java anonymous classes, which would behave the same way if the inner function were wrapped in an anonymous class instantiation and var i is replaced with an IntHolder (since Java anonymous class "closures" don't allow you to mutate local variables outside the anonymous class definition) – Andy
upvote
  flag
@JonCoombs do you think there actually are any languages where it would print 1 1 1 1 1 1? If it were an unknown language I would expect either 1 2 3 1 2 3 or a syntax error, but not 1 1 1 1 1 1. – Andy
upvote
  flag
Well, this academic because those other languages wouldn't look exactly like JS. The actual result above is exactly what I expected. My point is just that a programmer who is used to functions only seeing within their own scope might expect 1 1 1 1 1 1 at first glance. They'd probably have to do something like the following to actually compile it, which is admittedly different but is similar-looking and "feels like" the old-school equivalent: return function(int i) { console.log(i++); } – Jon Coombs

I believe in shorter explanations, so see the below image.

Enter image description here

function f1() ..> Light Red Box

function f2() ..> Red Small Box

Here we have two functions, f1() and f2(). f2() is inner to f1(). f1() has a variable, var x = 10.

When invoking the function f1(), f2() can access the value of var x = 10.

Here is the code:

function f1() {
    var x=10;

    function f2() {
        console.log(x)
    }

    return f2

}
f1()

f1() invoking here:

Enter image description here

upvote
  flag
This is already apparent to me from conventional scoping rules in C-style languages; how exactly does this demonstrate a closure? – Kenneth Worden
upvote
  flag
@KennethWorden What You Mean by a Closure ??? Its Very Simple Closure. Function f2() Can Access a variable out of its Scope Considered as A Closure – Dinesh Kanivu

The easiest use case I can think of to explain JavaScript closures is the Module Pattern. In the Module Pattern you define a function and call it immediately afterwards in what is called an Immediately Invoked Function Expression (IIFE). Everything that you write inside that function has private scope because it's defined inside the closure, thus allowing you to "simulate" privacy in JavaScript. Like so:

 var Closure = (function () {
    // This is a closure
    // Any methods, variables and properties you define here are "private"
    // and can't be accessed from outside the function.

    //This is a private variable
    var foo = "";

    //This is a private method
    var method = function(){

    }
})();

If, on the other hand, you'd like to make one or multiple variables or methods visible outside the closure, you can return them inside an object literal. Like so:

var Closure = (function () {
  // This is a closure
  // Any methods, variables and properties you define here are "private"
  // and can't be accessed from outside the function.

  //This is a private variable
  var foo = "";

  //This is a private method
  var method = function(){

  }

  //The method will be accessible from outside the closure
  return {
    method: method
  }

})();

Closure.method();

Hope it helps. Regards,

upvote
  flag
Though true, this doesn't really answer the question, as it only covers one simple case and doesn't really touch on the aspects that people find confusing, which typically relate to unexpected states/values. – Jon Coombs

Also... Perhaps we should cut your 27-year-old friend a little slack, because the entire concept of "closures" really is(!) ... voodoo!

By that I mean: (a) you do not, intuitively, expect it ...AND... (b) when someone takes the time to explain it to you, you certainly do not expect it to work!

Intuition tells you that "this must be nonsense... surely it must result in some kind of syntax-error or something!" How on earth(!) could you, in effect, "pull a function from 'the middle of' wherever-it's-at," such that you could [still!] actually have read/write access to the context of "wherever-it-was-at?!"

When you finally realize that such a thing is possible, then ... sure ... anyone's after-the-fact reaction would be: "whoa-a-a-a(!)... kew-el-l-l-l...(!!!)"

But there will be a "big counter-intuitive hurdle" to overcome, first. Intuition gives you plenty of utterly-plausible expectations that such a thing would be "of course, absolutely nonsensical and therefore quite impossible."

Like I said: "it's voodoo."

upvote
  flag
I was asked to review this response (which I think is brilliant) but I am torn as it serves to expand on the OP's initial question without providing an answer. – ilan berci
upvote
  flag
I think it's relevant, because the OP was "trying to explain to his friend" .. WHAT 'closures' ARE. Closures happen to be one of the things that I, myself found difficult to wrap my head around when I first encountered them. Many ideas in computer programming are intuitive. Closures are not. "Getting a pointer to a function," sure, that part's obvious. But for that function, when it executes, to magically have access to variables in the context that existed at the time the function-pointer was made?! Yet it is so. – Mike Robinson
upvote
  flag
I would agree that this is especially true for programmers who are already well aware from other languages of scope and of functions returning/completing. An average non-programmer might actually find closures 'intuitive' in certain examples. Still, a real understanding requires being aware of scope, and of closures as special scope objects, and even of how references interact with garbage collection. – Jon Coombs

A closure is a function within a function that has access to its "parent" function's variables and parameters.

Example:

function showPostCard(Sender, Receiver) {

    var PostCardMessage = " Happy Spring!!! Love, ";

    function PreparePostCard() {
        return "Dear " + Receiver + PostCardMessage + Sender;
    }

    return PreparePostCard();
}
showPostCard("Granny", "Olivia");

The children will always remember the secrets they have shared with their parents, even after their parents are gone. This is what closures are for functions.

The secrets for JavaScript functions are the private variables

var parent = function() {
 var name = "Mary"; // secret
}

Every time you call it, local variable "name" is created and given name "Mary". And every time the function exits the variable is lost and the name is forgotten.

As you may guess, because the variables are re-created every time the function is called, and nobody else will know them, there must be a secret place where they are stored. It could be called Chamber of Secrets or stack or local scope but it doesn't really matter. We know they are there, somewhere, hidden in the memory.

But, in JavaScript there is this very special thing that functions which are created inside other functions, can also know the local variables of their parents and keep them as long as they live.

var parent = function() {
  var name = "Mary";
  var child = function(childName) {
    // I can also see that "name" is "Mary"
  }
}

So, as long as we are in the parent -function, it can create one or more child functions which do share the secret variables from the secret place.

But the sad thing is, if the child is also a private variable of its parent function, it would also die when the parent ends, and the secrets would die with them.

So to live, the child has to leave before it's too late

var parent = function() {
  var name = "Mary";
  var child = function(childName) {
    return "My name is " + childName  +", child of " + name; 
  }
  return child; // child leaves the parent ->
}
var child = parent(); // < - and here it is outside 

And now, even though Mary is "no longer running", the memory of her is not lost and her child will always remember her name and other secrets they shared during their time together.

So, if you call the child "Alice", she will respond

child("Alice") => "My name is Alice, child of Mary"

That's all there is to tell.

14 upvote
  flag
This is the explanation that made the most sense to me because it doesn't assume significant prior knowledge of technical terms. The top-voted explanation here assumes the person who doesn't understand closures has a full and complete understanding of terms like 'lexical scope' and 'execution context' - while I can understand these conceptually, I don't think I'm as comfortable with the details of them as I should be, and the explanation with no jargon in it at all is what made closures finally click for me, thank you. As a bonus, I think it also explains what scope is very concisely. – Emma W

A closure is something many JavaScript developers use all the time, but we take it for granted. How it works is not that complicated. Understanding how to use it purposefully is complex.

At its simplest definition (as other answers have pointed out), a closure is basically a function defined inside another function. And that inner function has access to variables defined in the scope of the outer function. The most common practice that you'll see using closures is defining variables and functions in the global scope, and having access to those variables in the function scope of that function.

var x = 1;
function myFN() {
  alert(x); //1, as opposed to undefined.
}
// Or
function a() {
   var x = 1;
   function b() {
       alert(x); //1, as opposed to undefined.
   }
   b();
}

So what?

A closure isn't that special to a JavaScript user until you think about what life would be like without them. In other languages, variables used in a function get cleaned up when that function returns. In the above, x would have been a "null pointer", and you'd need to establish a getter and setter and start passing references. Doesn't sound like JavaScript right? Thank the mighty closure.

Why should I care?

You don't really have to be aware of closures to use them. But as others have also pointed out, they can be leveraged to create faux private variables. Until you get to needing private variables, just use them like you always have.

I like Kyle Simpson's definition of a closure:

Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.

Lexical scope is when an inner scope can access its outer scope.

Here is a modified example he provides in his book series 'You Don't Know JS: Scopes & Closures'.

function foo() {
  var a = 2;

  function bar() {
    console.log( a );
  }
  return bar;
}

function test() {
  var bz = foo();
  bz();
}

// prints 2. Here function bar referred by var bz is outside 
// its lexical scope but it can still access it
test(); 

The following example is a simple illustration of a JavaScript closure. This is the closure function, which returns a function, with access to its local variable x,

function outer(x){
     return function inner(y){
         return x+y;
     }
}

Invoke the function like this:

var add10 = outer(10);
add10(20); // The result will be 30
add10(40); // The result will be 50

var add20 = outer(20);
add20(20); // The result will be 40
add20(40); // The result will be 60

The author of Closures has explained closures pretty well, explaining the reason why we need them and also explaining LexicalEnvironment which is necessary to understanding closures.
Here is the summary:

What if a variable is accessed, but it isn’t local? Like here:

Enter image description here

In this case, the interpreter finds the variable in the outer LexicalEnvironment object.

The process consists of two steps:

  1. First, when a function f is created, it is not created in an empty space. There is a current LexicalEnvironment object. In the case above, it’s window (a is undefined at the time of function creation).

Enter image description here

When a function is created, it gets a hidden property, named [[Scope]], which references the current LexicalEnvironment.

Enter image description here

If a variable is read, but can not be found anywhere, an error is generated.

Nested functions

Functions can be nested one inside another, forming a chain of LexicalEnvironments which can also be called a scope chain.

Enter image description here

So, function g has access to g, a and f.

Closures

A nested function may continue to live after the outer function has finished:

Enter image description here

Marking up LexicalEnvironments:

Enter image description here

As we see, this.say is a property in the user object, so it continues to live after User completed.

And if you remember, when this.say is created, it (as every function) gets an internal reference this.say.[[Scope]] to the current LexicalEnvironment. So, the LexicalEnvironment of the current User execution stays in memory. All variables of User also are its properties, so they are also carefully kept, not junked as usually.

The whole point is to ensure that if the inner function wants to access an outer variable in the future, it is able to do so.

To summarize:

  1. The inner function keeps a reference to the outer LexicalEnvironment.
  2. The inner function may access variables from it any time even if the outer function is finished.
  3. The browser keeps the LexicalEnvironment and all its properties (variables) in memory until there is an inner function which references it.

This is called a closure.

(You may also want to read What is a practical use for a closure in JavaScript?)

Meet the illustrated explanation: How do JavaScript closures work behind the scenes.

The article explains how the scope objects (or LexicalEnvironments) are allocated and used in an intuitive way. Like, for this simple script:

"use strict";

var foo = 1;
var bar = 2;

function myFunc() {
  //-- Define local-to-function variables
  var a = 1;
  var b = 2;
  var foo = 3;
}

//-- And then, call it:
myFunc();

When executing the top-level code, we have the following arrangement of scope objects:

Enter image description here

And when myFunc() is called, we have the following scope chain:

Enter image description here

Understanding of how scope objects are created, used and deleted is a key to having a big picture and to understand how do closures work under the hood.

See the aforementioned article for all the details.

The best way is to explain these concepts incrementally:

Variables

console.log(x);
// undefined

Here, undefined is JavaScript's way of saying "I have no idea what x means."

Variables are like tags.

You can say, tag x points to value 42:

var x = 42;
console.log(x);
// 42

Now JavaScript knows what x means.

You can also re-assign a variable.

Make tag x point to a different value:

x = 43;
console.log(x);
// 43

Now x means something else.

Scope

When you make a function, the function has its own "box" for variables.

function A() {
  var x = 42;
}

console.log(x);

// undefined

From outside the box, you cannot see what's inside the box.

But from inside the box, you can see what's outside that box:

var x = 42;

function A() {
  console.log(x);
}

// 42

Inside function A, you have "scope access" to x.

Now if you have two boxes side-by-side:

function A() {
  var x = 42;
}

function B() {
  console.log(x);
}

// undefined

Inside function B, you have no access to variables inside function A.

But if you put define function B inside function A:

function A() {

  var x = 42;

  function B() {
    console.log(x);
  }

}

// 42

You now have "scope access".

Functions

In JavaScript, you run a function by calling it:

function A() {
  console.log(42);
}

Like this:

A();

// 42

Functions as Values

In JavaScript, you can point a tag to a function, just like pointing to a number:

var a = function() {
  console.log(42);
};

Variable a now means a function, you can run it.

a();
// 42

You can also pass this variable around:

setTimeout(a, 1000);

In a second (1000 milliseconds), the function a points to is called:

// 42

Closure Scope

Now when you define functions, those functions have access to their outer scopes.

When you pass functions around as values, it would be troublesome if that access is lost.

In JavaScript, functions keep their access to outer scope variables. Even when they are passed around to be run somewhere else.

var a = function() {

  var text = 'Hello!'

  var b = function() {
    console.log(text);
    // inside function `b`, you have access to `text`
  };

  // but you want to run `b` later, rather than right away
  setTimeout(b, 1000);

}

What happens now?

// 'Hello!'

Or consider this:

var c;

var a = function() {

  var text = 'Hello!'

  var b = function() {
    console.log(text);
    // inside function `b`, you have access to `text`
  };

  c = b;

}

// now we are out side of function `a`
// call `a` so the code inside `a` runs
a(); 

// now `c` has a value that is a function
// because what happened when `a` ran

// when you run `c`
c();

// 'Hello!'

You can still access variables in the closure scope.

Even though a has finished running, and now you are running c outside of a.

What just happened here is called 'closure' in JavaScript.

Pinocchio: Closures in 1883 (over a century before JavaScript)

I think it can best be explained to a 6-year-old with a nice adventure... The part of the Adventures of Pinocchio where Pinocchio is being swallowed by an oversized dogfish...

var tellStoryOfPinocchio = function(original) {

  // Prepare for exciting things to happen
  var pinocchioFindsMisterGeppetto;
  var happyEnding;

  // The story starts where Pinocchio searches for his 'father'
  var pinocchio = {
    name: 'Pinocchio',
    location: 'in the sea',
    noseLength: 2
  };

  // Is it a dog... is it a fish...
  // The dogfish appears, however there is no such concept as the belly
  // of the monster, there is just a monster...
  var terribleDogfish = {
    swallowWhole: function(snack) {
      // The swallowing of Pinocchio introduces a new environment (for the
      // things happening inside it)...
      // The BELLY closure... with all of its guts and attributes
      var mysteriousLightLocation = 'at Gepetto\'s ship';

      // Yes: in my version of the story the monsters mouth is directly
      // connected to its belly... This might explain the low ratings
      // I had for biology...
      var mouthLocation = 'in the monsters mouth and then outside';

      var puppet = snack;


      puppet.location = 'inside the belly';
      alert(snack.name + ' is swallowed by the terrible dogfish...');

      // Being inside the belly, Pinocchio can now experience new adventures inside it
      pinocchioFindsMisterGeppetto = function() {
        // The event of Pinocchio finding Mister Geppetto happens inside the
        // belly and so it makes sence that it refers to the things inside
        // the belly (closure) like the mysterious light and of course the
        // hero Pinocchio himself!
        alert(puppet.name + ' sees a mysterious light (also in the belly of the dogfish) in the distance and swims to it to find Mister Geppetto! He survived on ship supplies for two years after being swallowed himself. ');
        puppet.location = mysteriousLightLocation;

        alert(puppet.name + ' tells Mister Geppetto he missed him every single day! ');
        puppet.noseLength++;
      }

      happyEnding = function() {
        // The escape of Pinocchio and Mister Geppetto happens inside the belly:
        // it refers to Pinocchio and the mouth of the beast.
        alert('After finding Mister Gepetto, ' + puppet.name + ' and Mister Gepetto travel to the mouth of the monster.');
        alert('The monster sleeps with its mouth open above the surface of the water. They escape through its mouth. ');
        puppet.location = mouthLocation;
        if (original) {
          alert(puppet.name + ' is eventually hanged for his innumerable faults. ');
        } else {
          alert(puppet.name + ' is eventually turned into a real boy and they all lived happily ever after...');
        }
      }
    }
  }

  alert('Once upon a time...');
  alert('Fast forward to the moment that Pinocchio is searching for his \'father\'...');
  alert('Pinocchio is ' + pinocchio.location + '.');
  terribleDogfish.swallowWhole(pinocchio);
  alert('Pinocchio is ' + pinocchio.location + '.');
  pinocchioFindsMisterGeppetto();
  alert('Pinocchio is ' + pinocchio.location + '.');
  happyEnding();
  alert('Pinocchio is ' + pinocchio.location + '.');

  if (pinocchio.noseLength > 2)
    console.log('Hmmm... apparently a little white lie was told. ');
}

tellStoryOfPinocchio(false);

 

Closures are simple

You probably shouldn't tell a six-year old about closures, but if you do, you might say that closure gives an ability to gain access to a variable declared in some other function scope.

enter image description here

function getA() {
  var a = [];

  // this action happens later,
  // after the function returned
  // the `a` value
  setTimeout(function() {
    a.splice(0, 0, 1, 2, 3, 4, 5);
  });

  return a;
}

var a = getA();
out('What is `a` length?');
out('`a` length is ' + a.length);

setTimeout(function() {
  out('No wait...');
  out('`a` length is ' + a.length);
  out('OK :|')
});
<pre id="output"></pre>

<script>
  function out(k) {
    document.getElementById('output').innerHTML += '> ' + k + '\n';
  }
</script>

A closure is a function that has access to information from the environment it was defined in.

For some, the information is the value in the environment at the time of creation. For others, the information is the variables in the environment at the time of creation.

If the lexical environment that the closure refers to belongs to a function that has exited, then (in the case of a closure referring to the variables in the environment) those lexical variables will continue to exist for reference by the closure.

A closure can be thought of a special case of global variables -- with a private copy created just for the function.

Or it can be thought of as a method where the environment is a specific instance of an object whose properties are the variables in the environment.

The former (closure as environment) similar to the latter where the environment copy is a context variable passed to each function in the former, and the instance variables form a context variable in the latter.

So a closure is a way to call a function without having to specify the context explicitly as a parameter or as the object in a method invocation.

var closure = createclosure(varForClosure);
closure(param1);  // closure has access to whatever createclosure gave it access to,
                  // including the parameter storing varForClosure.

vs

var contextvar = varForClosure; // use a struct for storing more than one..
contextclosure(contextvar, param1);

vs

var contextobj = new contextclass(varForClosure);
contextobj->objclosure(param1);

For maintainable code, I recommend the object oriented way. However for a quick and easy set of tasks (for example creating a callback), a closure can become natural and more clear, especially in the context of lamda or anonymous functions.

A closure is a function having access to the parent scope, even after the parent function has closed.

var add = (function() {
  var counter = 0;
  return function() {
    return counter += 1;
  }
})();

add();
add();
add();
// The counter is now 3

Example explained:

  • The variable add is assigned the return value of a self-invoking function.
  • The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.
  • This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.
  • This is called a JavaScript closure. It makes it possible for a function to have "private" variables.
  • The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

Source

For a six-year-old ...

Do you know what objects are?

Objects are things that have properties and do stuff.

One of the most important things about closures is that they let you make objects in JavaScript. Objects in JavaScript are just functions and closures that lets JavaScript store the value of the property for the object once it has been created.

Objects are very useful and keep everything nice and organised. Different objects can do different jobs and working together objects can do complicated things.

It's lucky that JavaScript has closures for making objects, otherwise everything would become a messy nightmare.

Whatever facility we use to transport an inner function outside of its lexical scope, it will maintain a scope reference to where it was originally declared, and wherever we execute it, that closure will be exercised.

There once was a caveman

function caveman {

who had a very special rock,

var rock = "diamond";

You could not get the rock yourself because it was in the caveman's private cave. Only the caveman knew how to find and get the rock.

return {
    getRock: function() {
        return rock;
    }
};
}

Luckily, he was a friendly caveman, and if you were willing to wait for his return, he would gladly get it for you.

var friend = caveman();
var rock = friend.getRock();

Pretty smart caveman.

Closure can be private and public variables or functions.

var ClusureDemo = function() {
    //privare variables
    var localVa1, localVa2;

    //private functions
    var setVaOne = function(newVa) {
        localVa1 = newVa;
    },
    setVaTwo = function(newVa) {
        localVa2 = newVa;
    },
    getVaOne = function() {
        return localVa1;
    },
    getVaTwo = function() {
        return localVa2;
    };

    return {
        //public variables and functions
        outVaOne : localVa1,
        outVaTwo : localVa2,
        setVaOne : setVaOne,
        setVaTwo : setVaTwo,
        getVaOne : getVaOne,
        getVaTwo : getVaTwo
    };
};

//Test Demo
var app = new ClusureDemo();
app.outVaOne = 'Hello Variable One';
app.outVaTwo = 'Hello Variable Two';
app.setVaOne(app.outVaOne);
app.setVaTwo(app.outVaTwo);

alert(app.getVaOne());
alert(app.getVaTwo());

Demo

To understand closures you have to get down to the program and literally execute as if you are the run time. Let's look at this simple piece of code:

Enter image description here

JavaScript runs the code in two phases:

  • Compilation Phase // JavaScript is not a pure interpreted language
  • Execution Phase

When JavaScript goes through the compilation phase it extract out the declarations of variables and functions. This is called hoisting. Functions encountered in this phase are saved as text blobs in memory also known as lambda. After compilation JavaScript enters the execution phase where it assigns all the values and runs the function. To run the function it prepares the execution context by assigning memory from the heap and repeating the compilation and execution phase for the function. This memory area is called scope of the function. There is a global scope when execution starts. Scopes are the key in understanding closures.

In this example, in first go, variable a is defined and then f is defined in the compilation phase. All undeclared variables are saved in the global scope. In the execution phase f is called with an argument. f's scope is assigned and the compilation and execution phase is repeated for it.

Arguments are also saved in this local scope for f. Whenever a local execution context or scope is created it contain a reference pointer to its parent scope. All variable access follows this lexical scope chain to find its value. If a variable is not found in the local scope it follows the chain and find it in its parent scope. This is also why a local variable overrides variables in the parent scope. The parent scope is called the "Closure" for local a scope or function.

Here when g's scope is being set up it got a lexical pointer to its parents scope of f. The scope of f is the closure for g. In JavaScript, if there is some reference to functions, objects or scopes if you can reach them somehow, it will not get garbage collected. So when myG is running, it has a pointer to scope of f which is its closure. This area of memory will not get garbage collected even f has returned. This is a closure as far as the runtime is concerned.

SO WHAT IS A CLOSURE?

  • It is an implicit, permanent link between a function and its scope chain...
  • A function definition's (lambda) hidden [[scope]] reference.
  • Holds the scope chain (preventing garbage collection).
  • It is used and copied as the "outer environment reference" anytime the function is run.

IMPLICIT CLOSURE

var data = "My Data!";
setTimeout(function() {
  console.log(data); // Prints "My Data!"
}, 3000);

EXPLICIT CLOSURES

function makeAdder(n) {
  var inc = n;
  var sum = 0;
  return function add() {
    sum = sum + inc;
    return sum;
  };
}

var adder3 = makeAdder(3);

A very interesting talk on closures and more is Arindam Paul - JavaScript VM internals, EventLoop, Async and ScopeChains.

This is how a beginner wrapped one's head around Closures like a function is wrapped inside of a functions body also known as Closures.

Definition from the book Speaking JavaScript "A closure is a function plus the connection to the scope in which the function was created" -Dr.Axel Rauschmayer

So what could that look like? Here is an example

function newCounter() {
  var counter = 0;
   return function increment() {
    counter += 1;
   }
}

var counter1 = newCounter();
var counter2 = newCounter();

counter1(); // Number of events: 1
counter1(); // Number of events: 2
counter2(); // Number of events: 1
counter1(); // Number of events: 3

newCounter closes over increment, counter can be referenced to and accessed by increment.

counter1 and counter2 will keep track of their own value.

Simple but hopefully a clear perspective of what a closure is around all these great and advanced answers.

Functions containing no free variables are called pure functions.

Functions containing one or more free variables are called closures.

var pure = function pure(x){
  return x 
  // only own environment is used
}

var foo = "bar"

var closure = function closure(){
  return foo
  // foo is free variable from the outer environment
}

src: https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure

MDN explains it best I think:

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

A closure always has an outer function and an inner function. The inner function is where all the work happens, and the outer function is just the environment that preserves the scope where the inner function was created. In this way, the inner function of a closure 'remembers' the environment/scope in which it was created. The most classic example is a counter function:

var closure = function() {
  var count = 0;
  return function() {
    count++;
    console.log(count);
  };
};

var counter = closure();

counter() // returns 1
counter() // returns 2
counter() // returns 3

In the above code, count is preserved by the outer function (environment function), so that every time you call counter(), the inner function (work function) can increment it.

Closures allow JavaScript programmers to write better code. Creative, expressive, and concise. We frequently use closures in JavaScript, and, no matter our JavaScript experience, we undoubtedly encounter them time and again. Closures might appear complex but hopefully, after you read this, closures will be much more easily understood and thus more appealing for your everyday JavaScript programming tasks.

You should be familiar with JavaScript variable scope before you read further because to understand closures you must understand JavaScript’s variable scope.

What is a closure?

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

You create a closure by adding a function inside another function.

A Basic Example of Closures in JavaScript:

function showName (firstName, lastName) {

  var nameIntro = "Your name is ";
  // this inner function has access to the outer function's variables, including the parameter
  ​function makeFullName () {
            
​    return nameIntro + firstName + " " + lastName;
        
  }
​
​  return makeFullName ();

}

​
showName ("Michael", "Jackson"); // Your name is Michael Jackson


Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just about every piece of JavaScript code you read.

A Classic jQuery Example of Closures:

$(function() {
​
​  var selections = []; 
  $(".niners").click(function() { // this closure has access to the selections variable​
    selections.push (this.prop("name")); // update the selections variable in the outer function's scope​
  });
​});

Closures’ Rules and Side Effects

1. Closures have access to the outer function’s variable even after the outer function returns:

One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function later in your program. This example demonstrates:

function celebrityName (firstName) {
    var nameIntro = "This celebrity is ";
    // this inner function has access to the outer function's variables, including the parameter​
   function lastName (theLastName) {
        return nameIntro + firstName + " " + theLastName;
    }
    return lastName;
}
​
​var mjName = celebrityName ("Michael"); // At this juncture, the celebrityName outer function has returned.​
​
​// The closure (lastName) is called here after the outer function has returned above​
​// Yet, the closure still has access to the outer function's variables and parameter​
mjName ("Jackson"); // This celebrity is Michael Jackson


2. Closures store references to the outer function’s variables:

They do not store the actual value. 
Closures get more interesting when the value of the outer function’s variable changes before the closure is called. And this powerful feature can be harnessed in creative ways, such as this private variables example first demonstrated by Douglas Crockford:


function celebrityID () {
    var celebrityID = 999;
    // We are returning an object with some inner functions​
    // All the inner functions have access to the outer function's variables​
    return {
        getID: function ()  {
            // This inner function will return the UPDATED celebrityID variable​
            // It will return the current value of celebrityID, even after the changeTheID function changes it​
          return celebrityID;
        },
        setID: function (theNewID)  {
            // This inner function will change the outer function's variable anytime​
            celebrityID = theNewID;
        }
    }
​
}
​
​var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.​
mjID.getID(); // 999​
mjID.setID(567); // Changes the outer function's variable​
mjID.getID(); // 567: It returns the updated celebrityId variable


3. Closures Gone Awry

Because closures have access to the updated values of the outer function’s variables, they can also lead to bugs when the outer function’s variable changes with a for loop. Thus:

// This example is explained in detail below (just after this code box).​
​function celebrityIDCreator (theCelebrities) {
    var i;
    var uniqueID = 100;
    for (i = 0; i < theCelebrities.length; i++) {
      theCelebrities[i]["id"] = function ()  {
        return uniqueID + i;
      }
    }
    
    return theCelebrities;
}
​
​var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];
​
​var createIdForActionCelebs = celebrityIDCreator (actionCelebs);
​
​var stalloneID = createIdForActionCelebs [0];

    console.log(stalloneID.id()); // 103



More can be found here-

  1. http://javascript.info/tutorial/closures

  2. http://www.javascriptkit.com/javatutors/closures.shtml

Version picture for this answer: [Resolved]

Just forget about scope every thing and remember: When a variable needed somewhere, javascript will not destroy it. The variable always point to newest value.

Example 1:

enter image description here

Example 2:

enter image description here

Example 3: enter image description here

Closure are not difficult to understand. It depends only from the point of view.

I personally like to use them in cases of daily life.

function createCar()
{
    var rawMaterial = [/* lots of object */];
    function transformation(rawMaterials)
    {
       /* lots of changement here */
       return transformedMaterial;
    }
    var transformedMaterial = transformation(rawMaterial);
    function assemblage(transformedMaterial)
    {
        /*Assemblage of parts*/
        return car;
    }
    return assemblage(transformedMaterial);
}

We only need to go through certain steps in particular cases. As for the transformation of materials is only useful when you have the parts.

Closures are a somewhat advanced, and often misunderstood feature of the JavaScript language. Simply put, closures are objects that contain a function and a reference to the environment in which the function was created. However, in order to fully understand closures, there are two other features of the JavaScript language that must first be understood―first-class functions and inner functions.

First-Class Functions

In programming languages, functions are considered to be first-class citizens if they can be manipulated like any other data type. For example, first-class functions can be constructed at runtime and assigned to variables. They can also be passed to, and returned by other functions. In addition to meeting the previously mentioned criteria, JavaScript functions also have their own properties and methods. The following example shows some of the capabilities of first-class functions. In the example, two functions are created and assigned to the variables “foo” and “bar”. The function stored in “foo” displays a dialog box, while “bar” simply returns whatever argument is passed to it. The last line of the example does several things. First, the function stored in “bar” is called with “foo” as its argument. “bar” then returns the “foo” function reference. Finally, the returned “foo” reference is called, causing “Hello World!” to be displayed.

var foo = function() {
  alert("Hello World!");
};

var bar = function(arg) {
  return arg;
};

bar(foo)();

Inner Functions

Inner functions, also referred to as nested functions, are functions that are defined inside of another function (referred to as the outer function). Each time the outer function is called, an instance of the inner function is created. The following example shows how inner functions are used. In this case, add() is the outer function. Inside of add(), the doAdd() inner function is defined and called.

function add(value1, value2) {
  function doAdd(operand1, operand2) {
    return operand1 + operand2;
  }

  return doAdd(value1, value2);
}

var foo = add(1, 2);
// foo equals 3

One important characteristic of inner functions is that they have implicit access to the outer function’s scope. This means that the inner function can use the variables, arguments, etc. of the outer function. In the previous example, the “value1” and “value2” arguments of add() were passed to doAdd() as the “operand1” and “operand2” arguments. However, this is unnecessary because doAdd() has direct access to “value1” and “value2”. The previous example has been rewritten below to show how doAdd() can use “value1” and “value2”.

function add(value1, value2) {
  function doAdd() {
    return value1 + value2;
  }

  return doAdd();
}

var foo = add(1, 2);
// foo equals 3

Creating Closures

A closure is created when an inner function is made accessible from outside of the function that created it. This typically occurs when an outer function returns an inner function. When this happens, the inner function maintains a reference to the environment in which it was created. This means that it remembers all of the variables (and their values) that were in scope at the time. The following example shows how a closure is created and used.

function add(value1) {
  return function doAdd(value2) {
    return value1 + value2;
  };
}

var increment = add(1);
var foo = increment(2);
// foo equals 3

There are a number of things to note about this example.

The add() function returns its inner function doAdd(). By returning a reference to an inner function, a closure is created. “value1” is a local variable of add(), and a non-local variable of doAdd(). Non-local variables refer to variables that are neither in the local nor the global scope. “value2” is a local variable of doAdd(). When add(1) is called, a closure is created and stored in “increment”. In the closure’s referencing environment, “value1” is bound to the value one. Variables that are bound are also said to be closed over. This is where the name closure comes from. When increment(2) is called, the closure is entered. This means that doAdd() is called, with the “value1” variable holding the value one. The closure can essentially be thought of as creating the following function.

function increment(value2) {
  return 1 + value2;
}

When to Use Closures

Closures can be used to accomplish many things. They are very useful for things like configuring callback functions with parameters. This section covers two scenarios where closures can make your life as a developer much simpler.

Working With Timers

Closures are useful when used in conjunction with the setTimeout() and setInterval() functions. To be more specific, closures allow you to pass arguments to the callback functions of setTimeout() and setInterval(). For example, the following code prints the string “some message” once per second by calling showMessage().

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Closures</title>
  <meta charset="UTF-8" />
  <script>
    window.addEventListener("load", function() {
      window.setInterval(showMessage, 1000, "some message<br />");
    });

    function showMessage(message) {
      document.getElementById("message").innerHTML += message;
    }
  </script>
</head>
<body>
  <span id="message"></span>
</body>
</html>

Unfortunately, Internet Explorer does not support passing callback arguments via setInterval(). Instead of displaying “some message”, Internet Explorer displays “undefined” (since no value is actually passed to showMessage()). To work around this issue, a closure can be created which binds the “message” argument to the desired value. The closure can then be used as the callback function for setInterval(). To illustrate this concept, the JavaScript code from the previous example has been rewritten below to use a closure.

window.addEventListener("load", function() {
  var showMessage = getClosure("some message<br />");

  window.setInterval(showMessage, 1000);
});

function getClosure(message) {
  function showMessage() {
    document.getElementById("message").innerHTML += message;
  }

  return showMessage;
}

Emulating Private Data

Many object-oriented languages support the concept of private member data. However, JavaScript is not a pure object-oriented language and does not support private data. But, it is possible to emulate private data using closures. Recall that a closure contains a reference to the environment in which it was originally created―which is now out of scope. Since the variables in the referencing environment are only accessible from the closure function, they are essentially private data.

The following example shows a constructor for a simple Person class. When each Person is created, it is given a name via the “name” argument. Internally, the Person stores its name in the “_name” variable. Following good object-oriented programming practices, the method getName() is also provided for retrieving the name.

function Person(name) {
  this._name = name;

  this.getName = function() {
    return this._name;
  };
}

There is still one major problem with the Person class. Because JavaScript does not support private data, there is nothing stopping somebody else from coming along and changing the name. For example, the following code creates a Person named Colin, and then changes its name to Tom.

var person = new Person("Colin");

person._name = "Tom";
// person.getName() now returns "Tom"

Personally, I wouldn’t like it if just anyone could come along and legally change my name. In order to stop this from happening, a closure can be used to make the “_name” variable private. The Person constructor has been rewritten below using a closure. Note that “_name” is now a local variable of the Person constructor instead of an object property. A closure is formed because the outer function, Person() exposes an inner function by creating the public getName() method.

function Person(name) {
  var _name = name;

  this.getName = function() {
    return _name;
  };
}

Now, when getName() is called, it is guaranteed to return the value that was originally passed to the constructor. It is still possible for someone to add a new “_name” property to the object, but the internal workings of the object will not be affected as long as they refer to the variable bound by the closure. The following code shows that the “_name” variable is, indeed, private.

var person = new Person("Colin");

person._name = "Tom";
// person._name is "Tom" but person.getName() returns "Colin"

When Not to Use Closures

It is important to understand how closures work and when to use them. It is equally important to understand when they are not the right tool for the job at hand. Overusing closures can cause scripts to execute slowly and consume unnecessary memory. And because closures are so simple to create, it is possible to misuse them without even knowing it. This section covers several scenarios where closures should be used with caution.

In Loops

Creating closures within loops can have misleading results. An example of this is shown below. In this example, three buttons are created. When “button1” is clicked, an alert should be displayed that says “Clicked button 1”. Similar messages should be shown for “button2” and “button3”. However, when this code is run, all of the buttons show “Clicked button 4”. This is because, by the time one of the buttons is clicked, the loop has finished executing, and the loop variable has reached its final value of four.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Closures</title>
  <meta charset="UTF-8" />
  <script>
    window.addEventListener("load", function() {
      for (var i = 1; i < 4; i++) {
        var button = document.getElementById("button" + i);

        button.addEventListener("click", function() {
          alert("Clicked button " + i);
        });
      }
    });
  </script>
</head>
<body>
  <input type="button" id="button1" value="One" />
  <input type="button" id="button2" value="Two" />
  <input type="button" id="button3" value="Three" />
</body>
</html>

To solve this problem, the closure must be decoupled from the actual loop variable. This can be done by calling a new function, which in turn creates a new referencing environment. The following example shows how this is done. The loop variable is passed to the getHandler() function. getHandler() then returns a closure that is independent of the original “for” loop.

function getHandler(i) {
  return function handler() {
    alert("Clicked button " + i);
  };
}
window.addEventListener("load", function() {
  for (var i = 1; i < 4; i++) {
    var button = document.getElementById("button" + i);
    button.addEventListener("click", getHandler(i));
  }
});

Unnecessary Use in Constructors

Constructor functions are another common source of closure misuse. We’ve seen how closures can be used to emulate private data. However, it is overkill to implement methods as closures if they don’t actually access the private data. The following example revisits the Person class, but this time adds a sayHello() method which doesn’t use the private data.

function Person(name) {
  var _name = name;

  this.getName = function() {
    return _name;
  };

  this.sayHello = function() {
    alert("Hello!");
  };
}

Each time a Person is instantiated, time is spent creating the sayHello() method. If many Person objects are created, this becomes a waste of time. A better approach would be to add sayHello() to the Person prototype. By adding to the prototype, all Person objects can share the same method. This saves time in the constructor by not having to create a closure for each instance. The previous example is rewritten below with the extraneous closure moved into the prototype.

function Person(name) {
  var _name = name;

  this.getName = function() {
    return _name;
  };
}

Person.prototype.sayHello = function() {
  alert("Hello!");
};

Things to Remember

  • Closures contain a function and a reference to the environment in which the function was created.
  • A closure is formed when an outer function exposes an inner function. Closures can be used to easily pass parameters to callback functions.
  • Private data can be emulated by using closures. This is common in object-oriented programming and namespace design.
  • Closures should be not overused in constructors. Adding to the prototype is a better idea.

Link

My perspective of Closures:

Closures can be compared to a book, with a bookmark, on a bookshelf.

Suppose you have read a book, and you like some page in the book. You put in a bookmark at that page to track it.

Now once you finish reading the book, you do not need the book anymore, except, you want to have access to that page. You could have just cut out the page, but then you would loose the context on the story. So you put the book back in your bookshelf with the bookmark.

This is similar to a closure. The book is the outer function, and the page is your inner function, which gets returned, from the outer function. The bookmark is the reference to your page, and the context of the story is the lexical scope, which you need to retain. The bookshelf is the function stack, which cannot be cleaned up of the old books, till you hold onto the page.

Code Example:

function book() {
   var pages = [....]; //array of pages in your book
   var bookMarkedPage = 20; //bookmarked page number
   function getPage(){
       return pages[bookMarkedPage];
   }
   return getPage;
}

var myBook = book(),
    myPage = myBook.getPage();

When you run the book() function, you are allocating memory in the stack for the function to run in. But since it returns a function, the memory cannot be released, as the inner function has access to the variables from the context outside it, in this case 'pages' and 'bookMarkedPage'.

So effectively calling book() returns a reference to a closure, i.e not only a function, but a reference to the book and it's context, i.e. a reference to the function getPage, state of pages and bookMarkedPage variables.

Some points to consider:

Point 1: The bookshelf, just like the function stack has limited space, so use it wisely.

Point 2: Think about the fact, whether you need to hold onto the entire book when you just want to track a single page. You can release part of the memory, by not storing all the pages in the book when the closure is returned.

This is my perspective of Closures. Hope it helps, and if anyone thinks that this is not correct, please do let me know, as I am very interested to understand even more about scopes and closures!

Closures Understanding Starts With Scope Chain

To really understand what a closure is you need to understand what is the scope chain of a function. That totally helped me when I was struggling with closures. Stick to ready until the end and I am sure you'll master closures

The scope chain :

Every chunk of JavaScript code (global code or functions) has a scope chain associated with it. This scope chain is a list or chain of objects that defines the variables that are “in scope” for that code. When JavaScript needs to look up the value of a variable x (a process called variable resolution), it starts by looking at the first object in the chain. If that object has a property named x , the value of that property is used. If the first object does not have a property named x , JavaScript continues the search with the next object in the chain. If the second object does not have a property named x , the search moves on to the next object, and so on. If x is not a property of any of the objects in the scope chain, then x is not in scope for that code, and a ReferenceError occurs. In top-level JavaScript code (i.e., code not contained within any function definitions), the scope chain consists of a single object, the global object. In a non-nested function, the scope chain consists of two objects. The first is the object that defines the function’s parameters and local variables, and the second is the global object. In a nested function, the scope chain has three or more objects. It is important to understand how this chain of objects is created. When a function is DEFINED, it stores the scope chain then in effect. When that function is INVOKED, it creates a new object to store its local variables, and adds that new object to the stored scope chain to create a new, longer, chain that represents the scope for that function invocation. This becomes more interesting for nested functions because each time the outer function is called, the inner function is defined again. Since the scope chain differs on each invocation of the outer function, the inner function will be subtly different each time it is defined—the code of the inner function will be identical on each invocation of the outer function, but the scope chain associated with that code will be different. This notion of a scope chain is crucial for understanding closures .

Closures :

Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them. Most functions are invoked using the same scope chain that was in effect when the function was defined, and it doesn’t really matter that there is a closure involved. Closures become interesting when they are invoked under a different scope chain than the one that was in effect when they were defined. This happens most commonly when a nested function object is returned from the function within which it was defined. There are a number of powerful programming techniques that involve this kind of nested function closures, and their use has become relatively common in JavaScript programming. Closures may seem confusing when you first en- counter them, but it is important that you understand them well enough to use them comfortably.

Example :

var scope = "global scope"; // A global variable
function checkscope() {
  var scope = "local scope"; // A local variable
  function f() {
    return scope;
  } // Return the value in scope here
  return f();
}
checkscope(); // => "local scope"

The checkscope() function declares a local variable and then defines and invokes a function that returns the value of that variable. It should be clear to you why the call to checkscope() returns “local scope”. Now let’s change the code just slightly. Can you tell what this code will return?

In this code, a pair of parentheses has moved from inside checkscope() to outside of it. Instead of invoking the nested function and returning its result, checkscope() now just returns the nested function object itself. What happens when we invoke that nested function (with the second pair of parentheses in the last line of code) outside of the function in which it was defined? Remember the fundamental rule of lexical scoping: JavaScript functions are executed using the scope chain that was in effect when they were defined. The nested function f() was defined under a scope chain in which the variable scope was bound to the value “local scope”. That binding is still in effect when f is executed, wherever it is executed from. So the last line of code above returns “local scope”, not “global scope”. This, in a nutshell, is the surprising and powerful nature of closures: they capture the local variable (and parameter) bindings of the outer function within which they are defined.

Here is a concrete example of closure :

var uniqueInteger = (function() { // Define and invoke var counter = 0; // Private state of function below return function() { return counter++; }; })();

In order to understand this code, you have to read it carefully. At first glance, the first line of code looks like it is assigning a function to the variable uniqueInteger . In fact, the code is defining and invoking (as hinted by the open parenthesis on the first line) a function, so it is the return value of the function that is being assigned to uniqueInteger . Now, if we study the body of the function, we see that its return value is another function. It is this nested function object that gets assigned to uniqueInteger . The nested function has access to the variables in scope, and can use the counter variable defined in the outer function. Once that outer function returns, no other code can see the counter variable: the inner function has exclusive access to it.

Private variables like counter need not be exclusive to a single closure: it is perfectly possible for two or more nested functions to be defined within the same outer function and share the same scope chain. Consider the following code:

function counter() { var n = 0; return { count: function() { return n++; }, reset: function() { n = 0; } }; } var c = counter(), d = counter(); // Create two counters c.count(); // => 0 d.count(); // => 0: they count independently c.reset(); // reset() and count() methods share state c.count(); // => 0: because we reset c d.count(); // => 1: d was not reset

The counter() function returns a “counter” object. This object has two methods: count() returns the next integer, and reset() resets the internal state. The first thing to understand is that the two methods share access to the private variable n . The second thing to understand is that each invocation of counter() creates a new scope chain and a new private variable. So if you call counter() twice, you get two counter objects with different private variables. Calling count() or reset() on one counter object has no effect on the other.

Closures are easy to understand if you simply accept the lexical scoping rule: functions are executed using the scope chain that was in effect when they were defined. Some programmers find closures confusing, however, because they get caught up in imple- mentation details. Surely, they think, the local variables defined in the outer function cease to exist when the outer function returns, so how can the nested function execute using a scope chain that does not exist anymore? If you’re wondering about this your- self, then you have probably been exposed to low-level programming languages like C and to stack-based CPU architectures: if a function’s local variables are defined on a CPU stack, then they would indeed cease to exist when the function returned. But remember our definition of scope chain. We described it as a list of objects, not a stack of bindings. Each time a JavaScript function is invoked, a new object is created to hold the local variables for that invocation, and that object is added to the scope chain. When the function returns, that variable binding object is removed from the scope chain. If there were no nested functions, there are no more references to the binding object and it gets garbage collected. If there were nested functions defined, then each of those functions has a reference to the scope chain, and that scope chain refers to the variable binding object. If those nested functions objects remained within their outer function, however, then they themselves will be garbage collected, along with the variable binding object they referred to. But if the function defines a nested function and returns it or stores it into a property somewhere, then there will be an external reference to the nested function. It won’t be garbage collected, and the variable binding object it refers to won’t be garbage collected either.

A closure is simply when a function have access to its outside scope even after the scope's function has finished executing. Example:

function multiplier(n) {
    function multiply(x) {
          return n*x;
    }
    return mutliply;
}

var 10xmultiplier = multiplier(10);
var x = 10xmultiplier(5); // x= 50

we can see that even after multiplier has finished executing, the inner function multiply gets still access to the value of x which is 10 in this example.

A very common use of closures is currying (the same example above) where we spice our function progressively with parameters instead of supplying all of the arguments at once.

We can achieve this because Javascript (in addition to the prototypal OOP) allows as to program in a functional fashion where higher order functions can take other functions as arguments (fisrt class functions). functional programming in wikipedia

I highly recommend you to read this book by Kyle Simpson: 2 one part of the book series is dedicated to closures and it is called scope and closures. you don't know js: free reading on github

Let's start from here, As defined on MDN: Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.

Lexical scoping
Consider the following:

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function    
  }
  displayName();    
}
init();

init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is only available within the body of the init() function. The displayName() function has no local variables of its own. However, because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

function init() {
    var name = "Mozilla"; // name is a local variable created by init
    function displayName() { // displayName() is the inner function, a closure
        alert (name); // displayName() uses variable declared in the parent function    
    }
    displayName();    
}
init();

Run the code and notice that the alert() statement within the displayName() function successfully displays the value of the name variable, which is declared in its parent function. This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.

Closure
Now consider the following example:

function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

Running this code has exactly the same effect as the previous example of the init() function above: this time, the string "Mozilla" will be displayed in a JavaScript alert box. What's different — and interesting — is that the displayName() inner function is returned from the outer function before being executed.

At first glance, it may seem unintuitive that this code still works. In some programming languages, the local variables within a function exist only for the duration of that function's execution. Once makeFunc() has finished executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.

The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created. In this case, myFunc is a reference to the instance of the function displayName created when makeFunc is run. The instance of displayName maintains a reference to its lexical environment, within which the variable name exists. For this reason, when myFunc is invoked, the variable name remains available for use and "Mozilla" is passed to alert.

Here's a slightly more interesting example — a makeAdder function:

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

In this example, we have defined a function makeAdder(x), which takes a single argument, x, and returns a new function. The function it returns takes a single argument, y, and returns the sum of x and y.

In essence, makeAdder is a function factory — it creates functions which can add a specific value to their argument. In the above example we use our function factory to create two new functions — one that adds 5 to its argument, and one that adds 10.

add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.

Practical closures

Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.

Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.

For instance, suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body element in pixels, then set the size of the other elements on the page (such as headers) using the relative em unit:

body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}

h1 {
  font-size: 1.5em;
}

h2 {
  font-size: 1.2em;
}

Our interactive text size buttons can change the font-size property of the body element, and the adjustments will be picked up by other elements on the page thanks to the relative units. Here's the JavaScript:

function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

size12, size14, and size16 are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>


function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

for reading more about closures, visit the link on MDN

This answer is a summary of this youtube video Javascript Closures. So full credits to that video.

Closures are nothing but Stateful functions which maintain states of their private variables.

Normally when you make a call to a function as shown in the below figure. The variables are created on a stack ( running RAM memory) used and then disallocated.

enter image description here

But now there are situations where we want to maintain this state of the function thats where Javascript closures comes to use. A closure is a function inside function with a return call as shown in the below code.

enter image description here

So the closure code for the counter function above looks something as shown below.Its a function inside function with a return statement.

function Counter() {
           var counter = 0;

           var Increment = function () {
               counter++;
               alert(counter);
           }
           return {
               Increment
           }
       }

So now if you make a call the counter will increment in other words the function call maintains states.

var x = Counter(); // get the reference of the closure
x.Increment(); // Displays 1
x.Increment(); // Display 2 ( Maintains the private variables)

But now the biggest question whats the use of such stateful function. Stateful functions are building blocks to implement OOP concept like abstraction ,encapsulation and creating self contained modules.

So whatever you want encapsulated you can put it as private and things to be exposed to public should be put in return statement. Also these components are self contained isolated objects so they do not pollute global variables.

A object which follows OOP principles is self contained , follows abstraction , follows encapsulation and so. With out closures in Javascript this is difficult to implement.

enter image description here

A closure is a function having access to the parent scope, even after the parent function has closed.

So basically a closure is a function of another function. We can say like a child function.

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

The inner function has access not only to the outer function’s variables but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

You create a closure by adding a function inside another function.

Also, it's very useful method which is used in many famous frameworks including Angular, Node.js and jQuery:

Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just about every piece of JavaScript code you read.

But how the closures look like in a real-life coding? Look at this simple sample code:

function showName(firstName, lastName) {
      var nameIntro = "Your name is ";
      // this inner function has access to the outer function's variables, including the parameter
      function makeFullName() {
          return nameIntro + firstName + " " + lastName;
      }
      return makeFullName();
  }

  console.log(showName("Michael", "Jackson")); // Your name is Michael Jackson

Also, this is classic closure way in jQuery which every javascript and jQuery developers used it a lot:

$(function() {
    var selections = [];
    $(".niners").click(function() { // this closure has access to the selections variable
        selections.push(this.prop("name")); // update the selections variable in the outer function's scope
    });
});

But why we use closures? when we use it in an actual programming? what are the practical use of closures? the below is a good explanation and example by MDN:

Practical closures

Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.

Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.

For instance, suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body element in pixels, then set the size of the other elements on the page (such as headers) using the relative em unit:

Read the code below and run the code to see how closure help us here to easily make separate functions for each sections:

//javascript
function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
/*css*/
body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}

h1 {
  font-size: 1.5em;
}

h2 {
  font-size: 1.2em;
}
<!--html><!-->
<p>Some paragraph text</p>
<h1>some heading 1 text</h1>
<h2>some heading 2 text</h2>

<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>

For further study about closures, I recommend you to visit this page by MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Closures

Not the answer you're looking for? Browse other questions tagged or ask your own question.