By e-satis


2008-09-21 14:12:07 8 Comments

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.

30 comments

@Ali 2008-09-21 15:16:36

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.

@user2437417 2013-08-19 01:31:25

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

@Asad Saeeduddin 2013-08-20 17:51:46

@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

@Ry- 2014-07-04 14:53:35

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.

@Barth Zalewski 2014-09-18 10:45:56

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.

@Albert Gao 2016-08-18 00:26:28

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.

@Joel Anair 2008-09-21 14:18:18

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 theoretical or academically oriented explanations!

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

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.

An example of a closure

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

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

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


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

@e-satis 2008-09-21 14:38:40

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

@AnthonyWJones 2008-09-21 20:24:02

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.

@dlaliberte 2011-08-08 15:24:48

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

@Pawan 2012-07-12 17:56:38

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!

@dlaliberte 2013-02-11 18:20:22

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.

@Matt 2013-06-24 19:12: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.

@netusco 2014-03-21 22:51:34

would it be a fix for the 'list loop' to return the alert function on the result.push array?

@Andrew Macheret 2014-09-25 02:30:17

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

@Mark C. 2014-11-05 14:29:45

For example 7, why doesn't z = newClosure(4, obj)(2000); z(); work? Is it because function(x) is the return?

@Joel Anair 2014-11-05 14:55:56

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

@Mark C. 2014-11-05 14:58:17

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

@Joel Anair 2014-11-05 15:14:20

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

@caramba 2015-09-30 08:50:10

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

@jb1 2015-11-11 21:34:56

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"

@Scheintod 2015-12-28 08:37:56

Brilliantly explained. The one thing I'm missing is what happens to Objects passed to the creating function.

@user3290525 2016-01-19 00:25:39

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.

@Zlelik 2016-01-20 11:10:00

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?

@Joel Anair 2016-01-20 15:29:45

@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 2016-01-21 17:03:47

@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 2016-02-14 01:18:50

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

@Clay Nichols 2016-02-14 21:08:52

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

@Nier 2016-05-10 00:51:24

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.

@Bran 2016-05-13 03:27:29

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!

@Muntasir Alam 2016-07-02 23:02:53

Why do example 3 and 4 say they will log 667. When I run it I get either 43 or 42 respectively

@Rudey 2016-09-27 18:29:36

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?

@Joel Anair 2016-09-27 20:06:09

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

@Rozwel 2016-10-07 14:11:46

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.

@Benjamin 2017-01-30 12:27:47

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 stackoverflow.com/a/17809716/1859442

@user2598794 2017-05-15 12:44:22

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; }

@Return-1 2017-10-29 09:52:17

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.

@techie_28 2018-01-19 11:13:51

Just for my info. It is necessary that inner function's body is nested inside the parent.If the function reside elsewhere and is called by name inside parents body it wont get the access of parent. Is that correct?

@cglacet 2019-02-24 00:48:31

This explanation is way too long for what it is, the wikipedia page is a way better place to start if you don't understand closures. Start by explaining what it is (quoted from wikipedia): "A closure is a record storing a function together with an environment" then show a simple example and finally a concrete use case (pick any decorator you like as an example). With the way stackoverflow works I think that this response will sadly remain the first to be shown here.

@moha297 2013-05-04 16:06:00

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

@Florian Bösch 2008-09-21 14:20:29

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

@Flash 2013-01-04 02:59:32

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/…

@Thomas Eding 2015-03-18 03:38:09

Variables that are in the function's parameter list are also part of the closure (e.g. not just limited to var).

@almaruf 2019-05-23 12:37:10

Closures sound more like objects and classes etc. Not sure why don't a lot of people compare these two - would be easier for us novices to learn!

@Max Tkachenko 2013-06-06 10:22:55

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

@slartibartfast 2013-09-19 00:37:32

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.

@dlaliberte 2011-09-02 15:23:39

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

console.log(kitchen.getTrashBag()); // returns trash bag C
console.log(kitchen.getTrashBag()); // returns trash bag B
console.log(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.

@dlaliberte 2016-06-27 17:56:00

Actually, confusingly, the makeKitchen function call is the actual closure, not the kitchen object that it returns.

@Chetabahana 2016-08-12 15:12:01

Having my way through the others I found this answer as the easiest way to explain about what and why the closures.is.

@Staplerfahrer 2017-05-13 16:30:28

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

@Arvand 2015-08-15 13:38:59

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.

@Rafael Eyng 2015-04-08 21:27:52

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

--

From the book Eloquent JavaScript:

A good mental model is to think of function values as containing both the code in their body and the environment in which they are created. When called, the function body sees its original environment, not the environment in which the call is made.

@Alireza 2017-04-26 12:50:21

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

@jondavidjohn 2013-02-26 19:40:50

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)

@James Montagne 2013-02-26 19:51:22

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)

@e-satis 2013-02-27 11:20:09

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

@Chris22 2014-01-10 13:49:37

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

@Adam 2014-07-21 06:19:54

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!

@Dziamid 2015-03-08 19:32:34

+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?

@galileopy 2016-03-27 04:20:28

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.

@ivant 2016-05-12 07:23:52

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

@Brandon Søren Culley 2017-07-27 23:28:10

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.

@Jacob Swartwood 2011-06-24 18:49:16

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.

@Patrick M 2013-02-28 07:49:20

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.

@icc97 2016-02-23 00:58:37

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

@Jacob Swartwood 2016-03-01 16:00:04

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

@Merlin 2016-11-12 09:55:01

shouldn't it be var littleGirl = new princess() ?

@Jacob Swartwood 2016-12-05 21:40:14

That is not necessary @Lorenzo - this princess design is not a "class" but rather a "factory".

@user1559625 2017-06-19 06:32:33

@Patrick M but 'adventures' is an empty array, nothing is returned from 'princess' by 'story' function. what am i missing?

@Benjamin Krupp 2017-09-06 07:59:18

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

@Jacob Swartwood 2017-09-11 18:45:36

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

@Crystallize 2017-10-02 10:03:34

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.

@Tero Tolonen 2015-05-11 16:35:17

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.

@Emma W 2015-05-17 20:30:27

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.

@Shivprasad Koirala 2017-04-22 03:19:00

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

@Alireza 2017-04-10 10:59:57

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

@Chev 2013-06-19 20:45:55

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

@Alex Alexeev 2016-04-08 22:38:08

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.

@Rupam Datta 2017-10-16 10:25:19

Using let for var fixes the difference.

@TechnicalSmile 2017-12-29 10:17:01

Isn't here "Closure done right" is an example of "closure inside closure"?

@Chev 2017-12-29 18:52:58

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.

@Chev 2017-12-29 18:54:55

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.

@zak.http 2017-03-22 09:18:18

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

@Konrad Rudolph 2008-09-21 14:24:46

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.

@Ishmael 2010-04-08 14:16:40

I agree. Giving the functions meaningful names instead of the traditional "foobar" ones also helps me a lot. Semantics counts.

@Jus12 2010-12-22 09:52:33

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?

@Konrad Rudolph 2010-12-22 11:28:09

@Jus12: exactly. Behind the scenes, a closure is just some space where current variable values (“bindings”) are stored, as in your example.

@Matt 2013-06-21 12:36:49

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.

@Konrad Rudolph 2013-06-21 14:30:42

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

@Matt 2013-06-21 16:15:08

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

@Konrad Rudolph 2013-06-22 14:35:15

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

@Matt 2013-06-24 18:55:16

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

@Konrad Rudolph 2013-06-24 19:31:46

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

@Matt 2013-06-24 20:24:55

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

@poushy 2017-01-20 22:14:02

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!

@Alexis 2016-08-18 08:00:49

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.

@Abrar Jahin 2016-04-05 11:15:54

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

@Durgesh Pandey 2016-09-20 08:22:24

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

@christian Nguyen 2016-07-31 16:51:57

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

@Dinesh Kanivu 2015-04-17 07:41:15

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

@Dinesh Kanivu 2016-07-13 04:22:45

@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

@Matt 2013-06-25 22:22:24

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.

@Ronen Festinger 2016-10-07 05:02:17

What would happen if you called : second_calculator = first_calculator(); instead of second_calculator = make_calculator(); ? Should be the same, right?

@Matt 2016-10-10 09:49:48

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

@John Pick 2011-02-24 01:37:53

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.

@Shushanth Pallegar 2014-11-11 08:03:31

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

@grateful 2014-10-28 23:53:18

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.

@Ron Deijkers 2015-10-22 10:54:42

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

 

@Premraj 2015-11-05 12:15:17

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

@Gerardo Lima 2012-05-03 18:16:54

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

Related Questions

Sponsored Content

43 Answered Questions

[SOLVED] JavaScript closure inside loops – simple practical example

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

3 Answered Questions

22 Answered Questions

[SOLVED] Set a default parameter value for a JavaScript function

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5716381 View
  • 7108 Score
  • 79 Answer
  • Tags:   javascript arrays

24 Answered Questions

[SOLVED] What is the scope of variables in JavaScript?

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

17 Answered Questions

[SOLVED] How to decide when to use Node.js?

5 Answered Questions

[SOLVED] Is there a reason for C#'s reuse of the variable in a foreach?

Sponsored Content