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 BurtonMar 8 '13 at 17:22

53

@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 ReppenJun 26 '13 at 17:02

6

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 SchootenJun 19 '14 at 10:04

Two brief summaries

When a function (foo) declares other functions (bar and baz), the family of local variables created in foo is not destroyed when the function exits. The variables merely become invisible to the outside world. Foo can therefore cunningly return the functions bar and baz, and they can continue to read, write and communicate with each other through this closed-off family of variables ("the closure") that nobody else can meddle with, not even someone who calls foo again in future.

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.

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 of the outer function can remain accessible after returning from it. 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() have been secretly kept alive in a closure.

The genius 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 as though the stack-frame stays alive in memory even after the outer function exists!

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

Tricky: also note 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 6

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 may not act as you might first think.

You need to understand the "variable hoisting" feature in Javascript in order to understand this example.

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:

Note that when you run the example, "item2 undefined" is logged three times! This is because just like previous examples, there is only one closure for the local variables for buildList (which are result, i and item). 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.

It may be helpful to see what happens when a block-level declaration of the variable item is used (via the let keyword) instead of a function-scoped variable declaration via the var keyword. If that change is made, then each anonymous function in the array result has its own closure; when the example is run the output is as follows:

item0 undefined
item1 undefined
item2 undefined

If the variable i is also defined using let instead of var, then the output is:

item0 1
item1 2
item2 3

Example 7

In this final example, each call to the main function creates a separate closure.

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 to understand. 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 behavior 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 &mdash, and you can get closures at more than one level.

I think normally a closure is a 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.

Brilliant. I especially 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-satisSep 21 '08 at 14:38

36

@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.
– dlaliberteAug 8 '11 at 15:24

64

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.
– dlaliberteFeb 11 '13 at 18:20

21

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.
– MattJun 24 '13 at 19:12

151

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 MacheretSep 25 '14 at 2:30

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

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.

@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.
– user2437417Aug 19 '13 at 1:31

@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 SaeeduddinAug 20 '13 at 17:51

5

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.
– Ry-♦Jul 4 '14 at 14:53

7

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 ZalewskiSep 18 '14 at 10:45

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 GaoAug 18 '16 at 0:26

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.

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

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 MFeb 28 '13 at 7:49

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."
– icc97Feb 23 '16 at 0:58

12

@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 SwartwoodMar 1 '16 at 16:00

3

@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 SwartwoodSep 11 '17 at 18:45

3

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.
– CrystallizeOct 2 '17 at 10:03

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.

Actually, confusingly, the makeKitchen function call is the actual closure, not the kitchen object that it returns.
– dlaliberteJun 27 '16 at 17:56

3

Having my way through the others I found this answer as the easiest way to explain about what and why the closures.is.
– ChetabahanaAug 12 '16 at 15:12

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."
– StaplerfahrerMay 13 '17 at 16:30

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.

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

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 MontagneFeb 26 '13 at 19:51

37

@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-satisFeb 27 '13 at 11:20

76

"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.
– Chris22Jan 10 '14 at 13:49

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!
– AdamJul 21 '14 at 6:19

+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?
– DziamidMar 8 '15 at 19:32

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:

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 plus5carry its scope (or rather, its parent's scope) around. This way, x is well-defined and it is bound to the value 5.

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?
– Jus12Dec 22 '10 at 9:52

17

@Jus12: exactly. Behind the scenes, a closure is just some space where current variable values (“bindings”) are stored, as in your example.
– Konrad RudolphDec 22 '10 at 11:28

9

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.
– MattJun 21 '13 at 12:36

12

@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 RudolphJun 21 '13 at 14:30

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.

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.
– dlaliberteJul 21 '11 at 14:15

13

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.
– dlaliberteJul 10 '12 at 17:27

7

@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?
– dlaliberteOct 16 '12 at 16:06

5

@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.
– dlaliberteOct 18 '12 at 0:26

7

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.
– dlaliberteOct 21 '12 at 1:49

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.

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.
– slartibartfastSep 19 '13 at 0:37

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

assign it with var foo=1; or

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.

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 RhodeJul 31 '11 at 6:42

6

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.
– MixologicDec 30 '12 at 21:20

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.

What would happen if you called : second_calculator = first_calculator(); instead of second_calculator = make_calculator(); ? Should be the same, right?
– Ronen FestingerOct 7 '16 at 5:02

3

@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.
– MattOct 10 '16 at 9:49

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.

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.
– MossDec 6 '10 at 16:11

Seeing that innerFunction is not referenced outside outerFunction's scope, is the interpreter smart enough to see that it needs no closure?
– syockitMar 7 '11 at 5:49

8

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.
– dlaliberteAug 4 '11 at 14:01

4

@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 SaeeduddinAug 21 '13 at 13:41

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.

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.

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.

I mean, every function is technically a closure but the important part is that the function defines a new variable within. The function that get returns just references n created in a new closure. We just return a function so we can store it in the array and invoke it later.
– ChevDec 29 '17 at 18:52

If you want to just store the result in the array in the first iteration then you could inline it like this: arr[index] = (function (n) { return 'n = ' + n; })(index);. But then you're storing the resulting string in the array rather than a function to invoke which defeats the point of my example.
– ChevDec 29 '17 at 18:54

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

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.

This is the best explanation for JavaScript closures. Should be the chosen answer. The rest are entertaining enough but this one is actually useful in a practical way for real-world JavaScript coders.
– geoidesicFeb 4 '18 at 12:32

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.

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 WMay 17 '15 at 20:30

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.

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 CoombsMay 15 '15 at 1:34

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.
– ChevOct 29 '15 at 23:15

3

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 ONeillAug 9 '16 at 15:51

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.

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.
– dlaliberteJul 21 '11 at 14:03

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.
– pcorcoranSep 21 '08 at 22:29

21

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.
– dlaliberteAug 16 '12 at 2:39

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.

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:

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

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

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.

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

Closures

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

Marking up LexicalEnvironments:

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:

The inner function keeps a reference to the outer
LexicalEnvironment.

The inner function may access variables from it
any time even if the outer function is finished.

The browser keeps the LexicalEnvironment and all its properties (variables) in memory until there is an inner function which references it.

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.

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

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.

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.

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

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.

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.

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.

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'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.

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).