Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Like the old Albert Einstein said:

If you can't explain it to a six-year-old, you really don't understand it yourself.

Well, I tried to explain JavaScript closures to a 27-year-old friend and completely failed.

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

I have seen the Scheme example given on Stack Overflow, and it did not help.

share|improve this question
243  
Closures are a difficult concept to come to grips with on the first try. That's why SO is the perfect way to get this information in a coherent, straightforward series of well written explanations all from different perspectives. Ie; Send the 6-year old here to find the explanation that they understand. –  Jess Telford May 3 '12 at 1:35
8  
The title question "How do JavaScript closures work?" could be considered a much more complex question than what we find in the description, which is asking how you would explain (how to use) closures to a 6-year old. Maybe this explains why many of the answers are not really very simple, but nor are they complete or accurate. –  dlaliberte Aug 13 '12 at 17:11
30  
Practical explanation of closures - jondavidjohn.com/blog/2011/09/… –  jondavidjohn Sep 26 '12 at 16:31
108  
My problem with these and many answers is that they approach it from an abstract, theoretical perspective, rather than starting with explaining simply why closures are necessary in Javascript and the practical situations in which you use them. You end up with a tl;dr article that you have to slog through, all the time thinking, "but, why?". I would simply start with: closures are a neat way of dealing with the following two realities of JavaScript: a. scope is at the function level, not the block level and, b. much of what you do in practice in JavaScript is asynchronous/event driven. –  Jeremy Burton Mar 8 '13 at 17:22
8  
@Redsandro For one, it makes event-driven code a lot easier to write. I might fire a function when the page loads to determine specifics about the HTML or available features. I can define and set a handler in that function and have all that context info available every time the handler is called without having to re-query it. Solve the problem once, re-use on every page where that handler is needed with reduced overhead on handler re-invocation. You ever see the same data get re-mapped twice in a language that doesn't have them? Closures make it a lot easier to avoid that sort of thing. –  Erik Reppen Jun 26 '13 at 17:02

60 Answers 60

For a six-year-old?

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

000001 (jamiesHouse)

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

001 000001 (annVille.jamiesHouse)

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

01 001 000001 (myOldCountry.annVille.jamiesHouse)

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

000001 (jamiesHouse)

Spooky...

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

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

02 001 000001 (myNewCountry.annVille.jamiesHouse)

Opinions?

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

share|improve this answer

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

What is a Closure?

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

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

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

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

A closure is a stack-frame which is not deallocated when the function returns. (As if a 'stack-frame' were malloc'ed instead of being on the stack!)

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

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

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

Uses of Closures:

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

You can emulate the encapsulation concept in JavaScript using closures.

Closures are used extensively in jQuery and Node.js.

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

Example of Closures:

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

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

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

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

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

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

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

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

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

Example 3: Closures in jQuery

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

Useful Links:

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

share|improve this answer

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

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

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

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

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

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

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

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

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

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

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

share|improve this answer
1  
The "parallel" reference was quite useful for me (given my OOP background). For balance, it also helps if one also reads this: "Closures And Objects Are Equivalent" buff.ly/1gpPIBY –  lifebalance Mar 14 '14 at 12:13

In javascript Closures are awesome ,where variables or arguments are available to inner functions and they will be alive even after the outer functions 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
share|improve this answer

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

all other examples explained above are also very good to understand the concept.

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

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

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

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

MI2("Priyanka");
// alert 
// Raja - Mission Impossible 2, Seat - 1 
share|improve this answer

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

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

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

outerFunction();

ALERT: monkey

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

Now consider the following:

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

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

ALERT: monkey

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

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

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

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

outerFunction = null;
alert(referenceToInnerFunction());

ALERT: monkey ALERT: monkey

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

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

//////////

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

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

    innerFunction();
}

outerFunction();

ALERT: gorilla

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

share|improve this answer

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

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

share|improve this answer

From a personal blog post:

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

var a = 1;

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

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

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

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

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

var c = a(3);

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

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

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

var d = c(4);

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

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

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

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

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

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

var a = new Array();

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

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

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

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

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

The solution is:

var a = new Array();

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

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

share|improve this answer

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

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

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

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

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

share|improve this answer

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

Example:

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

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

  • It can be passed around as a value and

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

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

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

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

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

share|improve this answer

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

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

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

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

share|improve this answer

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

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

share|improve this answer
1  
It is not necessary to be the line before, you can declare a var or function in the same scope where you are declaring the function after that function declaration and it will see it too. JavaScript it is not a line interpreter. –  Juan Garcia Mar 19 '14 at 14:10

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

Let's imagine that a function is a room which wall are glass, but they are special glass, like the ones in an interrogation room. From outside they are opaque, from inside they are transparent. It can be rooms inside other rooms, and the only way of contact is a phone. If you call from outside, you don't know what is in it, but you know that the people inside will do a task if you give them certain information. They can see outside, so they can ask you for stuff that are outside and make changes to that stuff, but you can't change what it is inside from the outside, you don't even see (know) what it is inside. The people inside that room you are calling see what it is outside, but not what it is inside the rooms in that room, so they interact with them the way you are doing from outside. The people inside the most inner rooms can see many things, but the people of the most outer room don't even know about the most inner rooms existence.

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

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

share|improve this answer

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

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

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

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

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

share|improve this answer

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

It is like putting some coating around a function.

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

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

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

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

share|improve this answer

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

share|improve this answer

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

In JavaScript, it happens when you:

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

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

    $(div).click(displayMessage);
}
share|improve this answer

(not taking in account the 6 years old thing)

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.

share|improve this answer

Here's the most Zen answer I can give:

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

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

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

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

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

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

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

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

share|improve this answer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

share|improve this answer

maybe you should consider about object oriented structure instead of inner functions. eg:

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

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

share|improve this answer

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

Example:

function showPostCard(Sender, Receiver) {

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

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

    return PreparePostCard();
}
showPostCard("Granny", "Olivia");
share|improve this answer

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

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

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

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

    }
})();

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

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

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

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

  }

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

})();

Closure.method();

Hope it helps. Regards,

share|improve this answer

I believe in Lesser Explanation, So Se the Below Image enter image description here

function f1() ..> Light Red Box

function f2() ..> Red Small Box

Here We Have Two function, f1() and f2() f2() is inner to f1(). f1() has a variable var x=10.

when invoke the function f1(), f2() can access the value of var x=10

Here the Code

function f1()
{

var x=10;

    fun f2()
     {
       console.log(x) 

     }


}
f1()

f1() Invoking Here

enter image description here

share|improve this answer

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

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

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

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

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

Like I said: "it's voodoo."

share|improve this answer

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

share|improve this answer

The simplest, shortest, most easy to understand answer:

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

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

share|improve this answer

Closure is a reusable function: It seems also that you have learnt some languages where closures are available.

So let's us see the equivalence between closures of Groovy (for example) and closures of JavaScript.

Enter image description here

How to use:

  1. Groovy:

    [1,2,3].myEach{e->println e+3;}
    
  2. JavaScript:

    var list=[1,2,3].myEach(function(e){console.log(e+3);})
    

For Fiddling:

  1. Groovy:

    Closure such as JS

  2. JavaScript:

    http://jsfiddle.net/abdennour/kXtf4/1/ (jsFiddle)

share|improve this answer

protected by Community Sep 19 '11 at 16:35

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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