What is a 'Closure'?Can someone explain “access to modified closure” in C# in simple terms?Can someone define what a closure is in real world language?Javascript - What is the difference between self-invoking and the normal function invocation?Can someone explain to me what Closure is in ElixirAccess local variable from the global context?Is there a reason for C#'s reuse of the variable in a foreach?What is lexical scope?What is the difference between a 'closure' and a 'lambda'?If function A is required only by function B should A be defined inside B?When to use closure?What are MVP and MVC and what is the difference?What is a race condition?What is reflection and why is it useful?What is a monad?What is dependency injection?What is the difference between currying and partial application?What is the difference between a 'closure' and a 'lambda'?What is a plain English explanation of “Big O” notation?What is (functional) reactive programming?What is JSONP, and why was it created?

Using parameter substitution on a Bash array

If you attempt to grapple an opponent that you are hidden from, do they roll at disadvantage?

Personal Teleportation as a Weapon

Coordinate position not precise

Is there a problem with hiding "forgot password" until it's needed?

What is difference between behavior and behaviour

Transcription Beats per minute

How was Earth single-handedly capable of creating 3 of the 4 gods of chaos?

How could Frankenstein get the parts for his _second_ creature?

What's a natural way to say that someone works somewhere (for a job)?

Will it be accepted, if there is no ''Main Character" stereotype?

Efficiently merge handle parallel feature branches in SFDX

Can I Retrieve Email Addresses from BCC?

How will losing mobility of one hand affect my career as a programmer?

Best way to store options for panels

At which point does a character regain all their Hit Dice?

The plural of 'stomach"

Implement the Thanos sorting algorithm

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

when is out of tune ok?

How to be diplomatic in refusing to write code that breaches the privacy of our users

Can criminal fraud exist without damages?

Trouble understanding overseas colleagues

Is HostGator storing my password in plaintext?



What is a 'Closure'?


Can someone explain “access to modified closure” in C# in simple terms?Can someone define what a closure is in real world language?Javascript - What is the difference between self-invoking and the normal function invocation?Can someone explain to me what Closure is in ElixirAccess local variable from the global context?Is there a reason for C#'s reuse of the variable in a foreach?What is lexical scope?What is the difference between a 'closure' and a 'lambda'?If function A is required only by function B should A be defined inside B?When to use closure?What are MVP and MVC and what is the difference?What is a race condition?What is reflection and why is it useful?What is a monad?What is dependency injection?What is the difference between currying and partial application?What is the difference between a 'closure' and a 'lambda'?What is a plain English explanation of “Big O” notation?What is (functional) reactive programming?What is JSONP, and why was it created?













361















I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?










share|improve this question



















  • 18





    Now what exactly is the closure??? Some answers say, the closure is the function. Some say it is the stack. Some answers say, it is the "hidden" value. To my understanding, it is the function + enclosed variables.

    – Roland
    Nov 24 '09 at 15:18






  • 2





    Explains what a closure is: stackoverflow.com/questions/4103750/…

    – dietbuddha
    May 17 '11 at 15:51











  • Also have a look at What is a closure? at softwareengineering.stackexchange

    – B12Toaster
    Dec 29 '18 at 18:53
















361















I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?










share|improve this question



















  • 18





    Now what exactly is the closure??? Some answers say, the closure is the function. Some say it is the stack. Some answers say, it is the "hidden" value. To my understanding, it is the function + enclosed variables.

    – Roland
    Nov 24 '09 at 15:18






  • 2





    Explains what a closure is: stackoverflow.com/questions/4103750/…

    – dietbuddha
    May 17 '11 at 15:51











  • Also have a look at What is a closure? at softwareengineering.stackexchange

    – B12Toaster
    Dec 29 '18 at 18:53














361












361








361


207






I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?










share|improve this question
















I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?







functional-programming computer-science terminology glossary






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 2 '12 at 15:51


























community wiki





11 revs, 7 users 50%
Ben









  • 18





    Now what exactly is the closure??? Some answers say, the closure is the function. Some say it is the stack. Some answers say, it is the "hidden" value. To my understanding, it is the function + enclosed variables.

    – Roland
    Nov 24 '09 at 15:18






  • 2





    Explains what a closure is: stackoverflow.com/questions/4103750/…

    – dietbuddha
    May 17 '11 at 15:51











  • Also have a look at What is a closure? at softwareengineering.stackexchange

    – B12Toaster
    Dec 29 '18 at 18:53













  • 18





    Now what exactly is the closure??? Some answers say, the closure is the function. Some say it is the stack. Some answers say, it is the "hidden" value. To my understanding, it is the function + enclosed variables.

    – Roland
    Nov 24 '09 at 15:18






  • 2





    Explains what a closure is: stackoverflow.com/questions/4103750/…

    – dietbuddha
    May 17 '11 at 15:51











  • Also have a look at What is a closure? at softwareengineering.stackexchange

    – B12Toaster
    Dec 29 '18 at 18:53








18




18





Now what exactly is the closure??? Some answers say, the closure is the function. Some say it is the stack. Some answers say, it is the "hidden" value. To my understanding, it is the function + enclosed variables.

– Roland
Nov 24 '09 at 15:18





Now what exactly is the closure??? Some answers say, the closure is the function. Some say it is the stack. Some answers say, it is the "hidden" value. To my understanding, it is the function + enclosed variables.

– Roland
Nov 24 '09 at 15:18




2




2





Explains what a closure is: stackoverflow.com/questions/4103750/…

– dietbuddha
May 17 '11 at 15:51





Explains what a closure is: stackoverflow.com/questions/4103750/…

– dietbuddha
May 17 '11 at 15:51













Also have a look at What is a closure? at softwareengineering.stackexchange

– B12Toaster
Dec 29 '18 at 18:53






Also have a look at What is a closure? at softwareengineering.stackexchange

– B12Toaster
Dec 29 '18 at 18:53













16 Answers
16






active

oldest

votes


















585














Variable scope



When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.



function() 
var a = 1;
console.log(a); // works

console.log(a); // fails


If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.



var a = 1;
function()
console.log(a); // works

console.log(a); // works


When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.



This is how we normally expect things to work.



A closure is a persistent local variable scope



A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.



The scope object and all its local variables are tied to the function and will persist as long as that function persists.



This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.



For example



Here's a really simple example in JavaScript that illustrates the point:



outer = function() 
var a = 1;
var inner = function()
console.log(a);

return inner; // this returns a function


var fnc = outer(); // execute outer to get inner
fnc();


Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a. The variable a is in scope for the inner function.



Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.



Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.



As you might be able to guess, when I call fnc() it prints the value of a, which is "1".



In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.



In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.



a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outer. fnc is a variable which points to inner. a persists as long as fnc persists. a is within the closure.






share|improve this answer




















  • 88





    I thought this was a pretty good and easy to understand example.

    – user12345613
    Dec 28 '11 at 15:21






  • 11





    Thanks for the awesome explanation, I've seen many but this is the time I really got it.

    – Dimitar Dimitrov
    Apr 15 '13 at 9:04






  • 2





    Could I have an example of how this works in a library like JQuery as stated in the 2nd to last paragraph? I didn't totally understand that.

    – DPM
    Nov 8 '13 at 19:06






  • 4





    Hi Jubbat, yes, open up jquery.js and take a look at the first line. You'll see a function is opened. Now skip to the end, you'll see window.jQuery = window.$ = jQuery. Then the function is closed and self executed. You now have access to the $ function, which in turn has access to the other functions defined in the closure. Does that answer your question?

    – superluminary
    Nov 8 '13 at 21:48






  • 2





    Speaking on behalf of the new Swift community coming from the abandoned land of Objective-C: Thanks. This answer is perfection.

    – Adam Waite
    Jun 3 '14 at 23:46


















84














I'll give an example (in JavaScript):



function makeCounter () 
var count = 0;
return function ()
count += 1;
return count;



var x = makeCounter();

x(); returns 1

x(); returns 2

...etc...


What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time its called. Since we're not providing any parameters to x it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.



Here is my currying example again:



function add (a) 
return function (b)
return a + b;



var add3 = add(3);

add3(4); returns 7


What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3 it knows where to find the a value to perform the addition.






share|improve this answer




















  • 4





    IDK, what language (probably F#) you've used in above language. Could please give above example in pseudocode? I'm having hard time to understand this.

    – user
    May 13 '12 at 3:57






  • 1





    @crucifiedsoul It's Scheme. ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/intro.txt

    – Kyle Cronin
    May 13 '12 at 13:15






  • 3





    @KyleCronin Great example, thanks. Q: Is it more correct to say "the hidden value is called a closure", or is "the function that hides the value is the closure"? Or "the process of hiding the value is the closure"? Thanks!

    – Robert Hume
    Feb 24 '13 at 0:25







  • 2





    @RobertHume Good question. Semantically, the term "closure" is somewhat ambiguous. My personal definition is that the combination of both the hidden value and the enclosing function's use of it constitutes the closure.

    – Kyle Cronin
    Feb 24 '13 at 0:36






  • 1





    @KyleCronin Thanks -- I have a Scheme mid-term on Monday. :) Wanted to have the "closure" concept solid in my head. Thanks for posting this great answer to OP's question!

    – Robert Hume
    Feb 24 '13 at 0:52



















54














Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count) is available when the lambda function executes.






share|improve this answer




















  • 14





    It's not just the stack -- it's the enclosing lexical scope(s) that are preserved, regardless of whether they're stored on the stack or the heap (or both).

    – Matt Fenwick
    Nov 6 '12 at 13:16



















26














A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":



def outer (a):
b = "variable in outer()"
def inner (c):
print a, b, c
return inner

# Now the return value from outer() can be saved for later
func = outer ("test")
func (1) # prints "test variable in outer() 1





share|improve this answer






























    26














    First of all, contrary to what most of the people here tell you, closure is not a function! So what is it?

    It is a set of symbols defined in a function's "surrounding context" (known as its environment) which make it a CLOSED expression (that is, an expression in which every symbol is defined and has a value, so it can be evaluated).



    For example, when you have a JavaScript function:



    function closed(x) 
    return x + 3;



    it is a closed expression because all the symbols occurring in it are defined in it (their meanings are clear), so you can evaluate it. In other words, it is self-contained.



    But if you have a function like this:



    function open(x) 
    return x*y + 3;



    it is an open expression because there are symbols in it which has not been defined in it. Namely, y. When looking at this function, we can't tell what y is and what does it mean, we don't know its value, so we cannot evaluate this expression. I.e. we cannot call this function until we tell what y is supposed to mean in it. This y is called a free variable.



    This y begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its "surrounding context" (also known as the environment). At least that's what we hope for :P



    For example, it could be defined globally:



    var y = 7;

    function open(x)
    return x*y + 3;



    Or it could be defined in a function which wraps it:



    var global = 2;

    function wrapper(y)
    var w = "unused";

    return function(x)
    return x*y + 3;





    The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.



    In the example above, the inner function (which we didn't give a name because we didn't need it) is an open expression because the variable y in it is free – its definition is outside the function, in the function which wraps it. The environment for that anonymous function is the set of variables:




    global: 2,
    w: "unused",
    y: [whatever has been passed to that wrapper function as its parameter `y`]



    Now, the closure is that part of this environment which closes the inner function by supplying the definitions for all its free variables. In our case, the only free variable in the inner function was y, so the closure of that function is this subset of its environment:




    y: [whatever has been passed to that wrapper function as its parameter `y`]



    The other two symbols defined in the environment are not part of the closure of that function, because it doesn't require them to run. They are not needed to close it.



    More on the theory behind that here:
    https://stackoverflow.com/a/36878651/434562



    It's worth to note that in the example above, the wrapper function returns its inner function as a value. The moment we call this function can be remote in time from the moment the function has been defined (or created). In particular, its wrapping function is no longer running, and its parameters which has been on the call stack are no longer there :P This makes a problem, because the inner function needs y to be there when it is called! In other words, it requires the variables from its closure to somehow outlive the wrapper function and be there when needed. Therefore, the inner function has to make a snapshot of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)



    And this is why people often confuse the term closure to be that special type of function which can do such snapshots of the external variables they use, or the data structure used to store these variables for later. But I hope you understand now that they are not the closure itself – they're just ways to implement closures in a programming language, or language mechanisms which allows the variables from the function's closure to be there when needed. There's a lot of misconceptions around closures which (unnecessarily) make this subject much more confusing and complicated that it actually is.






    share|improve this answer

























    • An analogy that might help beginners to this is a closure ties up all the loose ends, which is what a person does when they seek closure (or it resolves all necessary references, or ...). Well, it helped me to think of it that way :o)

      – Will Crawford
      Mar 20 '18 at 18:35



















    23














    To help facilitate understanding of closures it might be useful to examine how they might be implemented in a procedural language. This explanation will follow a simplistic implementation of closures in Scheme.



    To start, I must introduce the concept of a namespace. When you enter a command into a Scheme interpreter, it must evaluate the various symbols in the expression and obtain their value. Example:



    (define x 3)

    (define y 4)

    (+ x y) returns 7


    The define expressions store the value 3 in the spot for x and the value 4 in the spot for y. Then when we call (+ x y), the interpreter looks up the values in the namespace and is able to perform the operation and return 7.



    However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:



    (define x 3)

    (define y 4)

    (let ((x 5))
    (+ x y)) returns 9

    x returns 3


    What the let keyword does is introduces a new namespace with x as the value 5. You will notice that it's still able to see that y is 4, making the sum returned to be 9. You can also see that once the expression has ended x is back to being 3. In this sense, x has been temporarily masked by the local value.



    Procedural and object-oriented languages have a similar concept. Whenever you declare a variable in a function that has the same name as a global variable you get the same effect.



    How would we implement this? A simple way is with a linked list - the head contains the new value and the tail contains the old namespace. When you need to look up a symbol, you start at the head and work your way down the tail.



    Now let's skip to the implementation of first-class functions for the moment. More or less, a function is a set of instructions to execute when the function is called culminating in the return value. When we read in a function, we can store these instructions behind the scenes and run them when the function is called.



    (define x 3)

    (define (plus-x y)
    (+ x y))

    (let ((x 5))
    (plus-x 4)) returns ?


    We define x to be 3 and plus-x to be its parameter, y, plus the value of x. Finally we call plus-x in an environment where x has been masked by a new x, this one valued 5. If we merely store the operation, (+ x y), for the function plus-x, since we're in the context of x being 5 the result returned would be 9. This is what's called dynamic scoping.



    However, Scheme, Common Lisp, and many other languages have what's called lexical scoping - in addition to storing the operation (+ x y) we also store the namespace at that particular point. That way, when we're looking up the values we can see that x, in this context, is really 3. This is a closure.



    (define x 3)

    (define (plus-x y)
    (+ x y))

    (let ((x 5))
    (plus-x 4)) returns 7


    In summary, we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables from enclosing scopes, as well as providing us the ability to locally mask a variable without affecting the rest of the program.






    share|improve this answer

























    • okay, thanks to your answer, I think that I finally have some idea what closure is about. But there is one big question: "we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables that otherwise would no longer be in scope." Why do we want to access variables that are out of scope? when we say let x = 5, we want x to be 5 and not 3. What is happening?

      – Lazer
      May 23 '10 at 11:28











    • @Laser: Sorry, that sentence didn't make much sense, so I updated it. I hope it makes more sense now. Also, don't think of the linked list as an implementation detail (as it's very inefficient) but as a simple way of conceptualize how it could be done.

      – Kyle Cronin
      May 23 '10 at 15:28


















    10














    Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.



    Function.prototype.delay = function(ms /*[, arg...]*/) 
    var fn = this,
    args = Array.prototype.slice.call(arguments, 1);

    return window.setTimeout(function()
    return fn.apply(fn, args);
    , ms);
    ;


    And here's how you would use it:



    var startPlayback = function(track) 
    Player.play(track);
    ;
    startPlayback(someTrack);


    Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:



    startPlayback.delay(5000, someTrack);
    // Keep going, do other things


    When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.

    This is a type of currying, or function decoration.



    Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readiblity of your code.






    share|improve this answer




















    • 1





      It should be noted that extending language or host objects is generally considered a bad thing as they are part of the global namespace

      – Jon Cooke
      May 29 '14 at 3:10


















    5














    Functions containing no free variables are called pure functions.



    Functions containing one or more free variables are called closures.



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


    var foo = "bar"

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



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






    share|improve this answer

























    • Why is this minused? It is actually much more "on the right track" with that distinction into free variables and bound variables, and pure/closed functions and impure/open functions, than most of the other clueless answers in here :P (discounting for confusing closures with functions being closed).

      – SasQ
      Apr 27 '16 at 2:43












    • I have no Idea, really. This is why StackOverflow sucks. Just look at the source of my Answer. Who could argue with that?

      – soundyogi
      Apr 27 '16 at 13:22


















    5














    tl;dr



    A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.



    In depth Wikipedia style explanation



    According to Wikipedia, a closure is:




    Techniques for implementing lexically scoped name binding in languages with first-class functions.




    What does that mean? Lets look into some definitions.



    I will explain closures and other related definitions by using this example:






    function startAt(x) 
    return function (y)
    return x + y;



    var closure1 = startAt(1);
    var closure2 = startAt(5);

    console.log(closure1(3)); // 4 (x == 1, y == 3)
    console.log(closure2(3)); // 8 (x == 5, y == 3)





    First-class functions



    Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.



    In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).



    Name binding



    Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.



    In the example above:



    • In the inner anonymous function's scope, y is bound to 3.

    • In startAt's scope, x is bound to 1 or 5 (depending on the closure).

    Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.



    Lexical scoping



    As Wikipedia says, the scope:




    Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.




    There are two techniques:



    • Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.

    • Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.

    For more explanation, check out this question and take a look at Wikipedia.



    In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.



    Wrapping (closuring) up



    In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.



    Now you should understand closures and how they behave, which is a fundamental part of JavaScript.



    Currying



    Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.






    share|improve this answer
































      4














      In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.



      def n_times(a_thing)
      return lambda a_thing * n
      end


      in the above code, lambda(|n| a_thing * n} is the closure because a_thing is referred by the lambda (an anonymous function creator).



      Now, if you put the resulting anonymous function in a function variable.



      foo = n_times(4)


      foo will break the normal scoping rule and start using 4 internally.



      foo.call(3)


      returns 12.






      share|improve this answer






























        2














        In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas Closure = Function pointer + Stack frame.



        .






        share|improve this answer
































          0














          Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.



          local old_dofile = dofile

          function dofile( filename )
          if filename == nil then
          error( 'Can not use default of stdin.' )
          end

          old_dofile( filename )
          end


          The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.






          share|improve this answer
































            0














            From Lua.org:




            When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.







            share|improve this answer
































              0














              If you are from the Java world, you can compare a closure with a member function of a class. Look at this example



              var f=function()
              var a=7;
              var g=function()
              return a;

              return g;



              The function g is a closure: g closes a in. So g can be compared with a member function, a can be compared with a class field, and the function f with a class.






              share|improve this answer
































                0














                Closures
                Whenever we have a function defined inside another function, the inner function has access to the variables declared
                in the outer function. Closures are best explained with examples.
                In Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the
                outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term
                closure. The concept in itself is simple enough and fairly intuitive.



                Listing 2-18:
                function outerFunction(arg)
                var variableInOuterFunction = arg;

                function bar()
                console.log(variableInOuterFunction); // Access a variable from the outer scope

                // Call the local function to demonstrate that it has access to arg
                bar();

                outerFunction('hello closure!'); // logs hello closure!


                source: http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf






                share|improve this answer
































                  0














                  Please have a look below code to understand closure in more deep:



                   for(var i=0; i< 5; i++) 
                  setTimeout(function()
                  console.log(i);
                  , 1000);



                  Here what will be output? 0,1,2,3,4 not that will be 5,5,5,5,5 because of closure



                  So how it will solve? Answer is below:



                   for(var i=0; i< 5; i++)
                  (function(j) //using IIFE
                  setTimeout(function()
                  console.log(j);
                  ,1000);
                  )(i);



                  Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute setTimeout function five time and print 5,5,5,5,5



                  Here how it solve using IIFE i.e Immediate Invoking Function Expression



                   (function(j) //i is passed here 
                  setTimeout(function()
                  console.log(j);
                  ,1000);
                  )(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4


                  For more, please understand execution context to understand closure.




                  • There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked



                     for(let i=0; i< 5; i++) 
                    setTimeout(function()
                    console.log(i);
                    ,1000);


                    Output: 0,1,2,3,4


                  => More explanation:



                  In memory, when for loop execute picture make like below:



                  Loop 1)



                   setTimeout(function()
                  console.log(i);
                  ,1000);


                  Loop 2)



                   setTimeout(function()
                  console.log(i);
                  ,1000);


                  Loop 3)



                   setTimeout(function()
                  console.log(i);
                  ,1000);


                  Loop 4)



                   setTimeout(function()
                  console.log(i);
                  ,1000);


                  Loop 5)



                   setTimeout(function()
                  console.log(i);
                  ,1000);


                  Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside setTimeout out five time it prints 5,5,5,5,5



                  so to resolve this use IIFE as explain above.






                  share|improve this answer

























                  • thanks for your answer. it would be more readable if you separated code from explanation. (don't indent lines that are not code)

                    – eMBee
                    Dec 15 '18 at 16:07










                  Your Answer






                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "1"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36636%2fwhat-is-a-closure%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  16 Answers
                  16






                  active

                  oldest

                  votes








                  16 Answers
                  16






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  585














                  Variable scope



                  When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.



                  function() 
                  var a = 1;
                  console.log(a); // works

                  console.log(a); // fails


                  If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.



                  var a = 1;
                  function()
                  console.log(a); // works

                  console.log(a); // works


                  When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.



                  This is how we normally expect things to work.



                  A closure is a persistent local variable scope



                  A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.



                  The scope object and all its local variables are tied to the function and will persist as long as that function persists.



                  This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.



                  For example



                  Here's a really simple example in JavaScript that illustrates the point:



                  outer = function() 
                  var a = 1;
                  var inner = function()
                  console.log(a);

                  return inner; // this returns a function


                  var fnc = outer(); // execute outer to get inner
                  fnc();


                  Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a. The variable a is in scope for the inner function.



                  Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.



                  Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.



                  As you might be able to guess, when I call fnc() it prints the value of a, which is "1".



                  In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.



                  In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.



                  a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outer. fnc is a variable which points to inner. a persists as long as fnc persists. a is within the closure.






                  share|improve this answer




















                  • 88





                    I thought this was a pretty good and easy to understand example.

                    – user12345613
                    Dec 28 '11 at 15:21






                  • 11





                    Thanks for the awesome explanation, I've seen many but this is the time I really got it.

                    – Dimitar Dimitrov
                    Apr 15 '13 at 9:04






                  • 2





                    Could I have an example of how this works in a library like JQuery as stated in the 2nd to last paragraph? I didn't totally understand that.

                    – DPM
                    Nov 8 '13 at 19:06






                  • 4





                    Hi Jubbat, yes, open up jquery.js and take a look at the first line. You'll see a function is opened. Now skip to the end, you'll see window.jQuery = window.$ = jQuery. Then the function is closed and self executed. You now have access to the $ function, which in turn has access to the other functions defined in the closure. Does that answer your question?

                    – superluminary
                    Nov 8 '13 at 21:48






                  • 2





                    Speaking on behalf of the new Swift community coming from the abandoned land of Objective-C: Thanks. This answer is perfection.

                    – Adam Waite
                    Jun 3 '14 at 23:46















                  585














                  Variable scope



                  When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.



                  function() 
                  var a = 1;
                  console.log(a); // works

                  console.log(a); // fails


                  If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.



                  var a = 1;
                  function()
                  console.log(a); // works

                  console.log(a); // works


                  When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.



                  This is how we normally expect things to work.



                  A closure is a persistent local variable scope



                  A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.



                  The scope object and all its local variables are tied to the function and will persist as long as that function persists.



                  This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.



                  For example



                  Here's a really simple example in JavaScript that illustrates the point:



                  outer = function() 
                  var a = 1;
                  var inner = function()
                  console.log(a);

                  return inner; // this returns a function


                  var fnc = outer(); // execute outer to get inner
                  fnc();


                  Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a. The variable a is in scope for the inner function.



                  Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.



                  Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.



                  As you might be able to guess, when I call fnc() it prints the value of a, which is "1".



                  In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.



                  In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.



                  a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outer. fnc is a variable which points to inner. a persists as long as fnc persists. a is within the closure.






                  share|improve this answer




















                  • 88





                    I thought this was a pretty good and easy to understand example.

                    – user12345613
                    Dec 28 '11 at 15:21






                  • 11





                    Thanks for the awesome explanation, I've seen many but this is the time I really got it.

                    – Dimitar Dimitrov
                    Apr 15 '13 at 9:04






                  • 2





                    Could I have an example of how this works in a library like JQuery as stated in the 2nd to last paragraph? I didn't totally understand that.

                    – DPM
                    Nov 8 '13 at 19:06






                  • 4





                    Hi Jubbat, yes, open up jquery.js and take a look at the first line. You'll see a function is opened. Now skip to the end, you'll see window.jQuery = window.$ = jQuery. Then the function is closed and self executed. You now have access to the $ function, which in turn has access to the other functions defined in the closure. Does that answer your question?

                    – superluminary
                    Nov 8 '13 at 21:48






                  • 2





                    Speaking on behalf of the new Swift community coming from the abandoned land of Objective-C: Thanks. This answer is perfection.

                    – Adam Waite
                    Jun 3 '14 at 23:46













                  585












                  585








                  585







                  Variable scope



                  When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.



                  function() 
                  var a = 1;
                  console.log(a); // works

                  console.log(a); // fails


                  If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.



                  var a = 1;
                  function()
                  console.log(a); // works

                  console.log(a); // works


                  When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.



                  This is how we normally expect things to work.



                  A closure is a persistent local variable scope



                  A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.



                  The scope object and all its local variables are tied to the function and will persist as long as that function persists.



                  This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.



                  For example



                  Here's a really simple example in JavaScript that illustrates the point:



                  outer = function() 
                  var a = 1;
                  var inner = function()
                  console.log(a);

                  return inner; // this returns a function


                  var fnc = outer(); // execute outer to get inner
                  fnc();


                  Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a. The variable a is in scope for the inner function.



                  Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.



                  Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.



                  As you might be able to guess, when I call fnc() it prints the value of a, which is "1".



                  In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.



                  In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.



                  a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outer. fnc is a variable which points to inner. a persists as long as fnc persists. a is within the closure.






                  share|improve this answer















                  Variable scope



                  When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them.



                  function() 
                  var a = 1;
                  console.log(a); // works

                  console.log(a); // fails


                  If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.



                  var a = 1;
                  function()
                  console.log(a); // works

                  console.log(a); // works


                  When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.



                  This is how we normally expect things to work.



                  A closure is a persistent local variable scope



                  A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.



                  The scope object and all its local variables are tied to the function and will persist as long as that function persists.



                  This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.



                  For example



                  Here's a really simple example in JavaScript that illustrates the point:



                  outer = function() 
                  var a = 1;
                  var inner = function()
                  console.log(a);

                  return inner; // this returns a function


                  var fnc = outer(); // execute outer to get inner
                  fnc();


                  Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a. The variable a is in scope for the inner function.



                  Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.



                  Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.



                  As you might be able to guess, when I call fnc() it prints the value of a, which is "1".



                  In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.



                  In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.



                  a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outer. fnc is a variable which points to inner. a persists as long as fnc persists. a is within the closure.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 15 '18 at 15:52


























                  community wiki





                  15 revs, 5 users 89%
                  superluminary








                  • 88





                    I thought this was a pretty good and easy to understand example.

                    – user12345613
                    Dec 28 '11 at 15:21






                  • 11





                    Thanks for the awesome explanation, I've seen many but this is the time I really got it.

                    – Dimitar Dimitrov
                    Apr 15 '13 at 9:04






                  • 2





                    Could I have an example of how this works in a library like JQuery as stated in the 2nd to last paragraph? I didn't totally understand that.

                    – DPM
                    Nov 8 '13 at 19:06






                  • 4





                    Hi Jubbat, yes, open up jquery.js and take a look at the first line. You'll see a function is opened. Now skip to the end, you'll see window.jQuery = window.$ = jQuery. Then the function is closed and self executed. You now have access to the $ function, which in turn has access to the other functions defined in the closure. Does that answer your question?

                    – superluminary
                    Nov 8 '13 at 21:48






                  • 2





                    Speaking on behalf of the new Swift community coming from the abandoned land of Objective-C: Thanks. This answer is perfection.

                    – Adam Waite
                    Jun 3 '14 at 23:46












                  • 88





                    I thought this was a pretty good and easy to understand example.

                    – user12345613
                    Dec 28 '11 at 15:21






                  • 11





                    Thanks for the awesome explanation, I've seen many but this is the time I really got it.

                    – Dimitar Dimitrov
                    Apr 15 '13 at 9:04






                  • 2





                    Could I have an example of how this works in a library like JQuery as stated in the 2nd to last paragraph? I didn't totally understand that.

                    – DPM
                    Nov 8 '13 at 19:06






                  • 4





                    Hi Jubbat, yes, open up jquery.js and take a look at the first line. You'll see a function is opened. Now skip to the end, you'll see window.jQuery = window.$ = jQuery. Then the function is closed and self executed. You now have access to the $ function, which in turn has access to the other functions defined in the closure. Does that answer your question?

                    – superluminary
                    Nov 8 '13 at 21:48






                  • 2





                    Speaking on behalf of the new Swift community coming from the abandoned land of Objective-C: Thanks. This answer is perfection.

                    – Adam Waite
                    Jun 3 '14 at 23:46







                  88




                  88





                  I thought this was a pretty good and easy to understand example.

                  – user12345613
                  Dec 28 '11 at 15:21





                  I thought this was a pretty good and easy to understand example.

                  – user12345613
                  Dec 28 '11 at 15:21




                  11




                  11





                  Thanks for the awesome explanation, I've seen many but this is the time I really got it.

                  – Dimitar Dimitrov
                  Apr 15 '13 at 9:04





                  Thanks for the awesome explanation, I've seen many but this is the time I really got it.

                  – Dimitar Dimitrov
                  Apr 15 '13 at 9:04




                  2




                  2





                  Could I have an example of how this works in a library like JQuery as stated in the 2nd to last paragraph? I didn't totally understand that.

                  – DPM
                  Nov 8 '13 at 19:06





                  Could I have an example of how this works in a library like JQuery as stated in the 2nd to last paragraph? I didn't totally understand that.

                  – DPM
                  Nov 8 '13 at 19:06




                  4




                  4





                  Hi Jubbat, yes, open up jquery.js and take a look at the first line. You'll see a function is opened. Now skip to the end, you'll see window.jQuery = window.$ = jQuery. Then the function is closed and self executed. You now have access to the $ function, which in turn has access to the other functions defined in the closure. Does that answer your question?

                  – superluminary
                  Nov 8 '13 at 21:48





                  Hi Jubbat, yes, open up jquery.js and take a look at the first line. You'll see a function is opened. Now skip to the end, you'll see window.jQuery = window.$ = jQuery. Then the function is closed and self executed. You now have access to the $ function, which in turn has access to the other functions defined in the closure. Does that answer your question?

                  – superluminary
                  Nov 8 '13 at 21:48




                  2




                  2





                  Speaking on behalf of the new Swift community coming from the abandoned land of Objective-C: Thanks. This answer is perfection.

                  – Adam Waite
                  Jun 3 '14 at 23:46





                  Speaking on behalf of the new Swift community coming from the abandoned land of Objective-C: Thanks. This answer is perfection.

                  – Adam Waite
                  Jun 3 '14 at 23:46













                  84














                  I'll give an example (in JavaScript):



                  function makeCounter () 
                  var count = 0;
                  return function ()
                  count += 1;
                  return count;



                  var x = makeCounter();

                  x(); returns 1

                  x(); returns 2

                  ...etc...


                  What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time its called. Since we're not providing any parameters to x it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.



                  Here is my currying example again:



                  function add (a) 
                  return function (b)
                  return a + b;



                  var add3 = add(3);

                  add3(4); returns 7


                  What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3 it knows where to find the a value to perform the addition.






                  share|improve this answer




















                  • 4





                    IDK, what language (probably F#) you've used in above language. Could please give above example in pseudocode? I'm having hard time to understand this.

                    – user
                    May 13 '12 at 3:57






                  • 1





                    @crucifiedsoul It's Scheme. ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/intro.txt

                    – Kyle Cronin
                    May 13 '12 at 13:15






                  • 3





                    @KyleCronin Great example, thanks. Q: Is it more correct to say "the hidden value is called a closure", or is "the function that hides the value is the closure"? Or "the process of hiding the value is the closure"? Thanks!

                    – Robert Hume
                    Feb 24 '13 at 0:25







                  • 2





                    @RobertHume Good question. Semantically, the term "closure" is somewhat ambiguous. My personal definition is that the combination of both the hidden value and the enclosing function's use of it constitutes the closure.

                    – Kyle Cronin
                    Feb 24 '13 at 0:36






                  • 1





                    @KyleCronin Thanks -- I have a Scheme mid-term on Monday. :) Wanted to have the "closure" concept solid in my head. Thanks for posting this great answer to OP's question!

                    – Robert Hume
                    Feb 24 '13 at 0:52
















                  84














                  I'll give an example (in JavaScript):



                  function makeCounter () 
                  var count = 0;
                  return function ()
                  count += 1;
                  return count;



                  var x = makeCounter();

                  x(); returns 1

                  x(); returns 2

                  ...etc...


                  What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time its called. Since we're not providing any parameters to x it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.



                  Here is my currying example again:



                  function add (a) 
                  return function (b)
                  return a + b;



                  var add3 = add(3);

                  add3(4); returns 7


                  What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3 it knows where to find the a value to perform the addition.






                  share|improve this answer




















                  • 4





                    IDK, what language (probably F#) you've used in above language. Could please give above example in pseudocode? I'm having hard time to understand this.

                    – user
                    May 13 '12 at 3:57






                  • 1





                    @crucifiedsoul It's Scheme. ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/intro.txt

                    – Kyle Cronin
                    May 13 '12 at 13:15






                  • 3





                    @KyleCronin Great example, thanks. Q: Is it more correct to say "the hidden value is called a closure", or is "the function that hides the value is the closure"? Or "the process of hiding the value is the closure"? Thanks!

                    – Robert Hume
                    Feb 24 '13 at 0:25







                  • 2





                    @RobertHume Good question. Semantically, the term "closure" is somewhat ambiguous. My personal definition is that the combination of both the hidden value and the enclosing function's use of it constitutes the closure.

                    – Kyle Cronin
                    Feb 24 '13 at 0:36






                  • 1





                    @KyleCronin Thanks -- I have a Scheme mid-term on Monday. :) Wanted to have the "closure" concept solid in my head. Thanks for posting this great answer to OP's question!

                    – Robert Hume
                    Feb 24 '13 at 0:52














                  84












                  84








                  84







                  I'll give an example (in JavaScript):



                  function makeCounter () 
                  var count = 0;
                  return function ()
                  count += 1;
                  return count;



                  var x = makeCounter();

                  x(); returns 1

                  x(); returns 2

                  ...etc...


                  What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time its called. Since we're not providing any parameters to x it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.



                  Here is my currying example again:



                  function add (a) 
                  return function (b)
                  return a + b;



                  var add3 = add(3);

                  add3(4); returns 7


                  What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3 it knows where to find the a value to perform the addition.






                  share|improve this answer















                  I'll give an example (in JavaScript):



                  function makeCounter () 
                  var count = 0;
                  return function ()
                  count += 1;
                  return count;



                  var x = makeCounter();

                  x(); returns 1

                  x(); returns 2

                  ...etc...


                  What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time its called. Since we're not providing any parameters to x it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.



                  Here is my currying example again:



                  function add (a) 
                  return function (b)
                  return a + b;



                  var add3 = add(3);

                  add3(4); returns 7


                  What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3 it knows where to find the a value to perform the addition.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 30 '16 at 2:20

























                  answered Aug 31 '08 at 4:49









                  Kyle CroninKyle Cronin

                  59.6k38137156




                  59.6k38137156







                  • 4





                    IDK, what language (probably F#) you've used in above language. Could please give above example in pseudocode? I'm having hard time to understand this.

                    – user
                    May 13 '12 at 3:57






                  • 1





                    @crucifiedsoul It's Scheme. ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/intro.txt

                    – Kyle Cronin
                    May 13 '12 at 13:15






                  • 3





                    @KyleCronin Great example, thanks. Q: Is it more correct to say "the hidden value is called a closure", or is "the function that hides the value is the closure"? Or "the process of hiding the value is the closure"? Thanks!

                    – Robert Hume
                    Feb 24 '13 at 0:25







                  • 2





                    @RobertHume Good question. Semantically, the term "closure" is somewhat ambiguous. My personal definition is that the combination of both the hidden value and the enclosing function's use of it constitutes the closure.

                    – Kyle Cronin
                    Feb 24 '13 at 0:36






                  • 1





                    @KyleCronin Thanks -- I have a Scheme mid-term on Monday. :) Wanted to have the "closure" concept solid in my head. Thanks for posting this great answer to OP's question!

                    – Robert Hume
                    Feb 24 '13 at 0:52













                  • 4





                    IDK, what language (probably F#) you've used in above language. Could please give above example in pseudocode? I'm having hard time to understand this.

                    – user
                    May 13 '12 at 3:57






                  • 1





                    @crucifiedsoul It's Scheme. ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/intro.txt

                    – Kyle Cronin
                    May 13 '12 at 13:15






                  • 3





                    @KyleCronin Great example, thanks. Q: Is it more correct to say "the hidden value is called a closure", or is "the function that hides the value is the closure"? Or "the process of hiding the value is the closure"? Thanks!

                    – Robert Hume
                    Feb 24 '13 at 0:25







                  • 2





                    @RobertHume Good question. Semantically, the term "closure" is somewhat ambiguous. My personal definition is that the combination of both the hidden value and the enclosing function's use of it constitutes the closure.

                    – Kyle Cronin
                    Feb 24 '13 at 0:36






                  • 1





                    @KyleCronin Thanks -- I have a Scheme mid-term on Monday. :) Wanted to have the "closure" concept solid in my head. Thanks for posting this great answer to OP's question!

                    – Robert Hume
                    Feb 24 '13 at 0:52








                  4




                  4





                  IDK, what language (probably F#) you've used in above language. Could please give above example in pseudocode? I'm having hard time to understand this.

                  – user
                  May 13 '12 at 3:57





                  IDK, what language (probably F#) you've used in above language. Could please give above example in pseudocode? I'm having hard time to understand this.

                  – user
                  May 13 '12 at 3:57




                  1




                  1





                  @crucifiedsoul It's Scheme. ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/intro.txt

                  – Kyle Cronin
                  May 13 '12 at 13:15





                  @crucifiedsoul It's Scheme. ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/intro.txt

                  – Kyle Cronin
                  May 13 '12 at 13:15




                  3




                  3





                  @KyleCronin Great example, thanks. Q: Is it more correct to say "the hidden value is called a closure", or is "the function that hides the value is the closure"? Or "the process of hiding the value is the closure"? Thanks!

                  – Robert Hume
                  Feb 24 '13 at 0:25






                  @KyleCronin Great example, thanks. Q: Is it more correct to say "the hidden value is called a closure", or is "the function that hides the value is the closure"? Or "the process of hiding the value is the closure"? Thanks!

                  – Robert Hume
                  Feb 24 '13 at 0:25





                  2




                  2





                  @RobertHume Good question. Semantically, the term "closure" is somewhat ambiguous. My personal definition is that the combination of both the hidden value and the enclosing function's use of it constitutes the closure.

                  – Kyle Cronin
                  Feb 24 '13 at 0:36





                  @RobertHume Good question. Semantically, the term "closure" is somewhat ambiguous. My personal definition is that the combination of both the hidden value and the enclosing function's use of it constitutes the closure.

                  – Kyle Cronin
                  Feb 24 '13 at 0:36




                  1




                  1





                  @KyleCronin Thanks -- I have a Scheme mid-term on Monday. :) Wanted to have the "closure" concept solid in my head. Thanks for posting this great answer to OP's question!

                  – Robert Hume
                  Feb 24 '13 at 0:52






                  @KyleCronin Thanks -- I have a Scheme mid-term on Monday. :) Wanted to have the "closure" concept solid in my head. Thanks for posting this great answer to OP's question!

                  – Robert Hume
                  Feb 24 '13 at 0:52












                  54














                  Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count) is available when the lambda function executes.






                  share|improve this answer




















                  • 14





                    It's not just the stack -- it's the enclosing lexical scope(s) that are preserved, regardless of whether they're stored on the stack or the heap (or both).

                    – Matt Fenwick
                    Nov 6 '12 at 13:16
















                  54














                  Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count) is available when the lambda function executes.






                  share|improve this answer




















                  • 14





                    It's not just the stack -- it's the enclosing lexical scope(s) that are preserved, regardless of whether they're stored on the stack or the heap (or both).

                    – Matt Fenwick
                    Nov 6 '12 at 13:16














                  54












                  54








                  54







                  Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count) is available when the lambda function executes.






                  share|improve this answer















                  Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count) is available when the lambda function executes.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 23 '17 at 12:26









                  Community

                  11




                  11










                  answered Aug 31 '08 at 9:08









                  Ben ChildsBen Childs

                  3,3471169




                  3,3471169







                  • 14





                    It's not just the stack -- it's the enclosing lexical scope(s) that are preserved, regardless of whether they're stored on the stack or the heap (or both).

                    – Matt Fenwick
                    Nov 6 '12 at 13:16













                  • 14





                    It's not just the stack -- it's the enclosing lexical scope(s) that are preserved, regardless of whether they're stored on the stack or the heap (or both).

                    – Matt Fenwick
                    Nov 6 '12 at 13:16








                  14




                  14





                  It's not just the stack -- it's the enclosing lexical scope(s) that are preserved, regardless of whether they're stored on the stack or the heap (or both).

                  – Matt Fenwick
                  Nov 6 '12 at 13:16






                  It's not just the stack -- it's the enclosing lexical scope(s) that are preserved, regardless of whether they're stored on the stack or the heap (or both).

                  – Matt Fenwick
                  Nov 6 '12 at 13:16












                  26














                  A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":



                  def outer (a):
                  b = "variable in outer()"
                  def inner (c):
                  print a, b, c
                  return inner

                  # Now the return value from outer() can be saved for later
                  func = outer ("test")
                  func (1) # prints "test variable in outer() 1





                  share|improve this answer



























                    26














                    A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":



                    def outer (a):
                    b = "variable in outer()"
                    def inner (c):
                    print a, b, c
                    return inner

                    # Now the return value from outer() can be saved for later
                    func = outer ("test")
                    func (1) # prints "test variable in outer() 1





                    share|improve this answer

























                      26












                      26








                      26







                      A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":



                      def outer (a):
                      b = "variable in outer()"
                      def inner (c):
                      print a, b, c
                      return inner

                      # Now the return value from outer() can be saved for later
                      func = outer ("test")
                      func (1) # prints "test variable in outer() 1





                      share|improve this answer













                      A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":



                      def outer (a):
                      b = "variable in outer()"
                      def inner (c):
                      print a, b, c
                      return inner

                      # Now the return value from outer() can be saved for later
                      func = outer ("test")
                      func (1) # prints "test variable in outer() 1






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 31 '08 at 4:54









                      John MillikinJohn Millikin

                      158k35191212




                      158k35191212





















                          26














                          First of all, contrary to what most of the people here tell you, closure is not a function! So what is it?

                          It is a set of symbols defined in a function's "surrounding context" (known as its environment) which make it a CLOSED expression (that is, an expression in which every symbol is defined and has a value, so it can be evaluated).



                          For example, when you have a JavaScript function:



                          function closed(x) 
                          return x + 3;



                          it is a closed expression because all the symbols occurring in it are defined in it (their meanings are clear), so you can evaluate it. In other words, it is self-contained.



                          But if you have a function like this:



                          function open(x) 
                          return x*y + 3;



                          it is an open expression because there are symbols in it which has not been defined in it. Namely, y. When looking at this function, we can't tell what y is and what does it mean, we don't know its value, so we cannot evaluate this expression. I.e. we cannot call this function until we tell what y is supposed to mean in it. This y is called a free variable.



                          This y begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its "surrounding context" (also known as the environment). At least that's what we hope for :P



                          For example, it could be defined globally:



                          var y = 7;

                          function open(x)
                          return x*y + 3;



                          Or it could be defined in a function which wraps it:



                          var global = 2;

                          function wrapper(y)
                          var w = "unused";

                          return function(x)
                          return x*y + 3;





                          The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.



                          In the example above, the inner function (which we didn't give a name because we didn't need it) is an open expression because the variable y in it is free – its definition is outside the function, in the function which wraps it. The environment for that anonymous function is the set of variables:




                          global: 2,
                          w: "unused",
                          y: [whatever has been passed to that wrapper function as its parameter `y`]



                          Now, the closure is that part of this environment which closes the inner function by supplying the definitions for all its free variables. In our case, the only free variable in the inner function was y, so the closure of that function is this subset of its environment:




                          y: [whatever has been passed to that wrapper function as its parameter `y`]



                          The other two symbols defined in the environment are not part of the closure of that function, because it doesn't require them to run. They are not needed to close it.



                          More on the theory behind that here:
                          https://stackoverflow.com/a/36878651/434562



                          It's worth to note that in the example above, the wrapper function returns its inner function as a value. The moment we call this function can be remote in time from the moment the function has been defined (or created). In particular, its wrapping function is no longer running, and its parameters which has been on the call stack are no longer there :P This makes a problem, because the inner function needs y to be there when it is called! In other words, it requires the variables from its closure to somehow outlive the wrapper function and be there when needed. Therefore, the inner function has to make a snapshot of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)



                          And this is why people often confuse the term closure to be that special type of function which can do such snapshots of the external variables they use, or the data structure used to store these variables for later. But I hope you understand now that they are not the closure itself – they're just ways to implement closures in a programming language, or language mechanisms which allows the variables from the function's closure to be there when needed. There's a lot of misconceptions around closures which (unnecessarily) make this subject much more confusing and complicated that it actually is.






                          share|improve this answer

























                          • An analogy that might help beginners to this is a closure ties up all the loose ends, which is what a person does when they seek closure (or it resolves all necessary references, or ...). Well, it helped me to think of it that way :o)

                            – Will Crawford
                            Mar 20 '18 at 18:35
















                          26














                          First of all, contrary to what most of the people here tell you, closure is not a function! So what is it?

                          It is a set of symbols defined in a function's "surrounding context" (known as its environment) which make it a CLOSED expression (that is, an expression in which every symbol is defined and has a value, so it can be evaluated).



                          For example, when you have a JavaScript function:



                          function closed(x) 
                          return x + 3;



                          it is a closed expression because all the symbols occurring in it are defined in it (their meanings are clear), so you can evaluate it. In other words, it is self-contained.



                          But if you have a function like this:



                          function open(x) 
                          return x*y + 3;



                          it is an open expression because there are symbols in it which has not been defined in it. Namely, y. When looking at this function, we can't tell what y is and what does it mean, we don't know its value, so we cannot evaluate this expression. I.e. we cannot call this function until we tell what y is supposed to mean in it. This y is called a free variable.



                          This y begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its "surrounding context" (also known as the environment). At least that's what we hope for :P



                          For example, it could be defined globally:



                          var y = 7;

                          function open(x)
                          return x*y + 3;



                          Or it could be defined in a function which wraps it:



                          var global = 2;

                          function wrapper(y)
                          var w = "unused";

                          return function(x)
                          return x*y + 3;





                          The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.



                          In the example above, the inner function (which we didn't give a name because we didn't need it) is an open expression because the variable y in it is free – its definition is outside the function, in the function which wraps it. The environment for that anonymous function is the set of variables:




                          global: 2,
                          w: "unused",
                          y: [whatever has been passed to that wrapper function as its parameter `y`]



                          Now, the closure is that part of this environment which closes the inner function by supplying the definitions for all its free variables. In our case, the only free variable in the inner function was y, so the closure of that function is this subset of its environment:




                          y: [whatever has been passed to that wrapper function as its parameter `y`]



                          The other two symbols defined in the environment are not part of the closure of that function, because it doesn't require them to run. They are not needed to close it.



                          More on the theory behind that here:
                          https://stackoverflow.com/a/36878651/434562



                          It's worth to note that in the example above, the wrapper function returns its inner function as a value. The moment we call this function can be remote in time from the moment the function has been defined (or created). In particular, its wrapping function is no longer running, and its parameters which has been on the call stack are no longer there :P This makes a problem, because the inner function needs y to be there when it is called! In other words, it requires the variables from its closure to somehow outlive the wrapper function and be there when needed. Therefore, the inner function has to make a snapshot of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)



                          And this is why people often confuse the term closure to be that special type of function which can do such snapshots of the external variables they use, or the data structure used to store these variables for later. But I hope you understand now that they are not the closure itself – they're just ways to implement closures in a programming language, or language mechanisms which allows the variables from the function's closure to be there when needed. There's a lot of misconceptions around closures which (unnecessarily) make this subject much more confusing and complicated that it actually is.






                          share|improve this answer

























                          • An analogy that might help beginners to this is a closure ties up all the loose ends, which is what a person does when they seek closure (or it resolves all necessary references, or ...). Well, it helped me to think of it that way :o)

                            – Will Crawford
                            Mar 20 '18 at 18:35














                          26












                          26








                          26







                          First of all, contrary to what most of the people here tell you, closure is not a function! So what is it?

                          It is a set of symbols defined in a function's "surrounding context" (known as its environment) which make it a CLOSED expression (that is, an expression in which every symbol is defined and has a value, so it can be evaluated).



                          For example, when you have a JavaScript function:



                          function closed(x) 
                          return x + 3;



                          it is a closed expression because all the symbols occurring in it are defined in it (their meanings are clear), so you can evaluate it. In other words, it is self-contained.



                          But if you have a function like this:



                          function open(x) 
                          return x*y + 3;



                          it is an open expression because there are symbols in it which has not been defined in it. Namely, y. When looking at this function, we can't tell what y is and what does it mean, we don't know its value, so we cannot evaluate this expression. I.e. we cannot call this function until we tell what y is supposed to mean in it. This y is called a free variable.



                          This y begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its "surrounding context" (also known as the environment). At least that's what we hope for :P



                          For example, it could be defined globally:



                          var y = 7;

                          function open(x)
                          return x*y + 3;



                          Or it could be defined in a function which wraps it:



                          var global = 2;

                          function wrapper(y)
                          var w = "unused";

                          return function(x)
                          return x*y + 3;





                          The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.



                          In the example above, the inner function (which we didn't give a name because we didn't need it) is an open expression because the variable y in it is free – its definition is outside the function, in the function which wraps it. The environment for that anonymous function is the set of variables:




                          global: 2,
                          w: "unused",
                          y: [whatever has been passed to that wrapper function as its parameter `y`]



                          Now, the closure is that part of this environment which closes the inner function by supplying the definitions for all its free variables. In our case, the only free variable in the inner function was y, so the closure of that function is this subset of its environment:




                          y: [whatever has been passed to that wrapper function as its parameter `y`]



                          The other two symbols defined in the environment are not part of the closure of that function, because it doesn't require them to run. They are not needed to close it.



                          More on the theory behind that here:
                          https://stackoverflow.com/a/36878651/434562



                          It's worth to note that in the example above, the wrapper function returns its inner function as a value. The moment we call this function can be remote in time from the moment the function has been defined (or created). In particular, its wrapping function is no longer running, and its parameters which has been on the call stack are no longer there :P This makes a problem, because the inner function needs y to be there when it is called! In other words, it requires the variables from its closure to somehow outlive the wrapper function and be there when needed. Therefore, the inner function has to make a snapshot of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)



                          And this is why people often confuse the term closure to be that special type of function which can do such snapshots of the external variables they use, or the data structure used to store these variables for later. But I hope you understand now that they are not the closure itself – they're just ways to implement closures in a programming language, or language mechanisms which allows the variables from the function's closure to be there when needed. There's a lot of misconceptions around closures which (unnecessarily) make this subject much more confusing and complicated that it actually is.






                          share|improve this answer















                          First of all, contrary to what most of the people here tell you, closure is not a function! So what is it?

                          It is a set of symbols defined in a function's "surrounding context" (known as its environment) which make it a CLOSED expression (that is, an expression in which every symbol is defined and has a value, so it can be evaluated).



                          For example, when you have a JavaScript function:



                          function closed(x) 
                          return x + 3;



                          it is a closed expression because all the symbols occurring in it are defined in it (their meanings are clear), so you can evaluate it. In other words, it is self-contained.



                          But if you have a function like this:



                          function open(x) 
                          return x*y + 3;



                          it is an open expression because there are symbols in it which has not been defined in it. Namely, y. When looking at this function, we can't tell what y is and what does it mean, we don't know its value, so we cannot evaluate this expression. I.e. we cannot call this function until we tell what y is supposed to mean in it. This y is called a free variable.



                          This y begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its "surrounding context" (also known as the environment). At least that's what we hope for :P



                          For example, it could be defined globally:



                          var y = 7;

                          function open(x)
                          return x*y + 3;



                          Or it could be defined in a function which wraps it:



                          var global = 2;

                          function wrapper(y)
                          var w = "unused";

                          return function(x)
                          return x*y + 3;





                          The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.



                          In the example above, the inner function (which we didn't give a name because we didn't need it) is an open expression because the variable y in it is free – its definition is outside the function, in the function which wraps it. The environment for that anonymous function is the set of variables:




                          global: 2,
                          w: "unused",
                          y: [whatever has been passed to that wrapper function as its parameter `y`]



                          Now, the closure is that part of this environment which closes the inner function by supplying the definitions for all its free variables. In our case, the only free variable in the inner function was y, so the closure of that function is this subset of its environment:




                          y: [whatever has been passed to that wrapper function as its parameter `y`]



                          The other two symbols defined in the environment are not part of the closure of that function, because it doesn't require them to run. They are not needed to close it.



                          More on the theory behind that here:
                          https://stackoverflow.com/a/36878651/434562



                          It's worth to note that in the example above, the wrapper function returns its inner function as a value. The moment we call this function can be remote in time from the moment the function has been defined (or created). In particular, its wrapping function is no longer running, and its parameters which has been on the call stack are no longer there :P This makes a problem, because the inner function needs y to be there when it is called! In other words, it requires the variables from its closure to somehow outlive the wrapper function and be there when needed. Therefore, the inner function has to make a snapshot of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)



                          And this is why people often confuse the term closure to be that special type of function which can do such snapshots of the external variables they use, or the data structure used to store these variables for later. But I hope you understand now that they are not the closure itself – they're just ways to implement closures in a programming language, or language mechanisms which allows the variables from the function's closure to be there when needed. There's a lot of misconceptions around closures which (unnecessarily) make this subject much more confusing and complicated that it actually is.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited May 23 '17 at 11:55


























                          community wiki





                          3 revs, 2 users 98%
                          SasQ













                          • An analogy that might help beginners to this is a closure ties up all the loose ends, which is what a person does when they seek closure (or it resolves all necessary references, or ...). Well, it helped me to think of it that way :o)

                            – Will Crawford
                            Mar 20 '18 at 18:35


















                          • An analogy that might help beginners to this is a closure ties up all the loose ends, which is what a person does when they seek closure (or it resolves all necessary references, or ...). Well, it helped me to think of it that way :o)

                            – Will Crawford
                            Mar 20 '18 at 18:35

















                          An analogy that might help beginners to this is a closure ties up all the loose ends, which is what a person does when they seek closure (or it resolves all necessary references, or ...). Well, it helped me to think of it that way :o)

                          – Will Crawford
                          Mar 20 '18 at 18:35






                          An analogy that might help beginners to this is a closure ties up all the loose ends, which is what a person does when they seek closure (or it resolves all necessary references, or ...). Well, it helped me to think of it that way :o)

                          – Will Crawford
                          Mar 20 '18 at 18:35












                          23














                          To help facilitate understanding of closures it might be useful to examine how they might be implemented in a procedural language. This explanation will follow a simplistic implementation of closures in Scheme.



                          To start, I must introduce the concept of a namespace. When you enter a command into a Scheme interpreter, it must evaluate the various symbols in the expression and obtain their value. Example:



                          (define x 3)

                          (define y 4)

                          (+ x y) returns 7


                          The define expressions store the value 3 in the spot for x and the value 4 in the spot for y. Then when we call (+ x y), the interpreter looks up the values in the namespace and is able to perform the operation and return 7.



                          However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:



                          (define x 3)

                          (define y 4)

                          (let ((x 5))
                          (+ x y)) returns 9

                          x returns 3


                          What the let keyword does is introduces a new namespace with x as the value 5. You will notice that it's still able to see that y is 4, making the sum returned to be 9. You can also see that once the expression has ended x is back to being 3. In this sense, x has been temporarily masked by the local value.



                          Procedural and object-oriented languages have a similar concept. Whenever you declare a variable in a function that has the same name as a global variable you get the same effect.



                          How would we implement this? A simple way is with a linked list - the head contains the new value and the tail contains the old namespace. When you need to look up a symbol, you start at the head and work your way down the tail.



                          Now let's skip to the implementation of first-class functions for the moment. More or less, a function is a set of instructions to execute when the function is called culminating in the return value. When we read in a function, we can store these instructions behind the scenes and run them when the function is called.



                          (define x 3)

                          (define (plus-x y)
                          (+ x y))

                          (let ((x 5))
                          (plus-x 4)) returns ?


                          We define x to be 3 and plus-x to be its parameter, y, plus the value of x. Finally we call plus-x in an environment where x has been masked by a new x, this one valued 5. If we merely store the operation, (+ x y), for the function plus-x, since we're in the context of x being 5 the result returned would be 9. This is what's called dynamic scoping.



                          However, Scheme, Common Lisp, and many other languages have what's called lexical scoping - in addition to storing the operation (+ x y) we also store the namespace at that particular point. That way, when we're looking up the values we can see that x, in this context, is really 3. This is a closure.



                          (define x 3)

                          (define (plus-x y)
                          (+ x y))

                          (let ((x 5))
                          (plus-x 4)) returns 7


                          In summary, we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables from enclosing scopes, as well as providing us the ability to locally mask a variable without affecting the rest of the program.






                          share|improve this answer

























                          • okay, thanks to your answer, I think that I finally have some idea what closure is about. But there is one big question: "we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables that otherwise would no longer be in scope." Why do we want to access variables that are out of scope? when we say let x = 5, we want x to be 5 and not 3. What is happening?

                            – Lazer
                            May 23 '10 at 11:28











                          • @Laser: Sorry, that sentence didn't make much sense, so I updated it. I hope it makes more sense now. Also, don't think of the linked list as an implementation detail (as it's very inefficient) but as a simple way of conceptualize how it could be done.

                            – Kyle Cronin
                            May 23 '10 at 15:28















                          23














                          To help facilitate understanding of closures it might be useful to examine how they might be implemented in a procedural language. This explanation will follow a simplistic implementation of closures in Scheme.



                          To start, I must introduce the concept of a namespace. When you enter a command into a Scheme interpreter, it must evaluate the various symbols in the expression and obtain their value. Example:



                          (define x 3)

                          (define y 4)

                          (+ x y) returns 7


                          The define expressions store the value 3 in the spot for x and the value 4 in the spot for y. Then when we call (+ x y), the interpreter looks up the values in the namespace and is able to perform the operation and return 7.



                          However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:



                          (define x 3)

                          (define y 4)

                          (let ((x 5))
                          (+ x y)) returns 9

                          x returns 3


                          What the let keyword does is introduces a new namespace with x as the value 5. You will notice that it's still able to see that y is 4, making the sum returned to be 9. You can also see that once the expression has ended x is back to being 3. In this sense, x has been temporarily masked by the local value.



                          Procedural and object-oriented languages have a similar concept. Whenever you declare a variable in a function that has the same name as a global variable you get the same effect.



                          How would we implement this? A simple way is with a linked list - the head contains the new value and the tail contains the old namespace. When you need to look up a symbol, you start at the head and work your way down the tail.



                          Now let's skip to the implementation of first-class functions for the moment. More or less, a function is a set of instructions to execute when the function is called culminating in the return value. When we read in a function, we can store these instructions behind the scenes and run them when the function is called.



                          (define x 3)

                          (define (plus-x y)
                          (+ x y))

                          (let ((x 5))
                          (plus-x 4)) returns ?


                          We define x to be 3 and plus-x to be its parameter, y, plus the value of x. Finally we call plus-x in an environment where x has been masked by a new x, this one valued 5. If we merely store the operation, (+ x y), for the function plus-x, since we're in the context of x being 5 the result returned would be 9. This is what's called dynamic scoping.



                          However, Scheme, Common Lisp, and many other languages have what's called lexical scoping - in addition to storing the operation (+ x y) we also store the namespace at that particular point. That way, when we're looking up the values we can see that x, in this context, is really 3. This is a closure.



                          (define x 3)

                          (define (plus-x y)
                          (+ x y))

                          (let ((x 5))
                          (plus-x 4)) returns 7


                          In summary, we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables from enclosing scopes, as well as providing us the ability to locally mask a variable without affecting the rest of the program.






                          share|improve this answer

























                          • okay, thanks to your answer, I think that I finally have some idea what closure is about. But there is one big question: "we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables that otherwise would no longer be in scope." Why do we want to access variables that are out of scope? when we say let x = 5, we want x to be 5 and not 3. What is happening?

                            – Lazer
                            May 23 '10 at 11:28











                          • @Laser: Sorry, that sentence didn't make much sense, so I updated it. I hope it makes more sense now. Also, don't think of the linked list as an implementation detail (as it's very inefficient) but as a simple way of conceptualize how it could be done.

                            – Kyle Cronin
                            May 23 '10 at 15:28













                          23












                          23








                          23







                          To help facilitate understanding of closures it might be useful to examine how they might be implemented in a procedural language. This explanation will follow a simplistic implementation of closures in Scheme.



                          To start, I must introduce the concept of a namespace. When you enter a command into a Scheme interpreter, it must evaluate the various symbols in the expression and obtain their value. Example:



                          (define x 3)

                          (define y 4)

                          (+ x y) returns 7


                          The define expressions store the value 3 in the spot for x and the value 4 in the spot for y. Then when we call (+ x y), the interpreter looks up the values in the namespace and is able to perform the operation and return 7.



                          However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:



                          (define x 3)

                          (define y 4)

                          (let ((x 5))
                          (+ x y)) returns 9

                          x returns 3


                          What the let keyword does is introduces a new namespace with x as the value 5. You will notice that it's still able to see that y is 4, making the sum returned to be 9. You can also see that once the expression has ended x is back to being 3. In this sense, x has been temporarily masked by the local value.



                          Procedural and object-oriented languages have a similar concept. Whenever you declare a variable in a function that has the same name as a global variable you get the same effect.



                          How would we implement this? A simple way is with a linked list - the head contains the new value and the tail contains the old namespace. When you need to look up a symbol, you start at the head and work your way down the tail.



                          Now let's skip to the implementation of first-class functions for the moment. More or less, a function is a set of instructions to execute when the function is called culminating in the return value. When we read in a function, we can store these instructions behind the scenes and run them when the function is called.



                          (define x 3)

                          (define (plus-x y)
                          (+ x y))

                          (let ((x 5))
                          (plus-x 4)) returns ?


                          We define x to be 3 and plus-x to be its parameter, y, plus the value of x. Finally we call plus-x in an environment where x has been masked by a new x, this one valued 5. If we merely store the operation, (+ x y), for the function plus-x, since we're in the context of x being 5 the result returned would be 9. This is what's called dynamic scoping.



                          However, Scheme, Common Lisp, and many other languages have what's called lexical scoping - in addition to storing the operation (+ x y) we also store the namespace at that particular point. That way, when we're looking up the values we can see that x, in this context, is really 3. This is a closure.



                          (define x 3)

                          (define (plus-x y)
                          (+ x y))

                          (let ((x 5))
                          (plus-x 4)) returns 7


                          In summary, we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables from enclosing scopes, as well as providing us the ability to locally mask a variable without affecting the rest of the program.






                          share|improve this answer















                          To help facilitate understanding of closures it might be useful to examine how they might be implemented in a procedural language. This explanation will follow a simplistic implementation of closures in Scheme.



                          To start, I must introduce the concept of a namespace. When you enter a command into a Scheme interpreter, it must evaluate the various symbols in the expression and obtain their value. Example:



                          (define x 3)

                          (define y 4)

                          (+ x y) returns 7


                          The define expressions store the value 3 in the spot for x and the value 4 in the spot for y. Then when we call (+ x y), the interpreter looks up the values in the namespace and is able to perform the operation and return 7.



                          However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:



                          (define x 3)

                          (define y 4)

                          (let ((x 5))
                          (+ x y)) returns 9

                          x returns 3


                          What the let keyword does is introduces a new namespace with x as the value 5. You will notice that it's still able to see that y is 4, making the sum returned to be 9. You can also see that once the expression has ended x is back to being 3. In this sense, x has been temporarily masked by the local value.



                          Procedural and object-oriented languages have a similar concept. Whenever you declare a variable in a function that has the same name as a global variable you get the same effect.



                          How would we implement this? A simple way is with a linked list - the head contains the new value and the tail contains the old namespace. When you need to look up a symbol, you start at the head and work your way down the tail.



                          Now let's skip to the implementation of first-class functions for the moment. More or less, a function is a set of instructions to execute when the function is called culminating in the return value. When we read in a function, we can store these instructions behind the scenes and run them when the function is called.



                          (define x 3)

                          (define (plus-x y)
                          (+ x y))

                          (let ((x 5))
                          (plus-x 4)) returns ?


                          We define x to be 3 and plus-x to be its parameter, y, plus the value of x. Finally we call plus-x in an environment where x has been masked by a new x, this one valued 5. If we merely store the operation, (+ x y), for the function plus-x, since we're in the context of x being 5 the result returned would be 9. This is what's called dynamic scoping.



                          However, Scheme, Common Lisp, and many other languages have what's called lexical scoping - in addition to storing the operation (+ x y) we also store the namespace at that particular point. That way, when we're looking up the values we can see that x, in this context, is really 3. This is a closure.



                          (define x 3)

                          (define (plus-x y)
                          (+ x y))

                          (let ((x 5))
                          (plus-x 4)) returns 7


                          In summary, we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables from enclosing scopes, as well as providing us the ability to locally mask a variable without affecting the rest of the program.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Jan 23 '11 at 0:21

























                          answered Aug 31 '08 at 16:30









                          Kyle CroninKyle Cronin

                          59.6k38137156




                          59.6k38137156












                          • okay, thanks to your answer, I think that I finally have some idea what closure is about. But there is one big question: "we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables that otherwise would no longer be in scope." Why do we want to access variables that are out of scope? when we say let x = 5, we want x to be 5 and not 3. What is happening?

                            – Lazer
                            May 23 '10 at 11:28











                          • @Laser: Sorry, that sentence didn't make much sense, so I updated it. I hope it makes more sense now. Also, don't think of the linked list as an implementation detail (as it's very inefficient) but as a simple way of conceptualize how it could be done.

                            – Kyle Cronin
                            May 23 '10 at 15:28

















                          • okay, thanks to your answer, I think that I finally have some idea what closure is about. But there is one big question: "we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables that otherwise would no longer be in scope." Why do we want to access variables that are out of scope? when we say let x = 5, we want x to be 5 and not 3. What is happening?

                            – Lazer
                            May 23 '10 at 11:28











                          • @Laser: Sorry, that sentence didn't make much sense, so I updated it. I hope it makes more sense now. Also, don't think of the linked list as an implementation detail (as it's very inefficient) but as a simple way of conceptualize how it could be done.

                            – Kyle Cronin
                            May 23 '10 at 15:28
















                          okay, thanks to your answer, I think that I finally have some idea what closure is about. But there is one big question: "we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables that otherwise would no longer be in scope." Why do we want to access variables that are out of scope? when we say let x = 5, we want x to be 5 and not 3. What is happening?

                          – Lazer
                          May 23 '10 at 11:28





                          okay, thanks to your answer, I think that I finally have some idea what closure is about. But there is one big question: "we can use a linked list to store the state of the namespace at the time of function definition, allowing us to access variables that otherwise would no longer be in scope." Why do we want to access variables that are out of scope? when we say let x = 5, we want x to be 5 and not 3. What is happening?

                          – Lazer
                          May 23 '10 at 11:28













                          @Laser: Sorry, that sentence didn't make much sense, so I updated it. I hope it makes more sense now. Also, don't think of the linked list as an implementation detail (as it's very inefficient) but as a simple way of conceptualize how it could be done.

                          – Kyle Cronin
                          May 23 '10 at 15:28





                          @Laser: Sorry, that sentence didn't make much sense, so I updated it. I hope it makes more sense now. Also, don't think of the linked list as an implementation detail (as it's very inefficient) but as a simple way of conceptualize how it could be done.

                          – Kyle Cronin
                          May 23 '10 at 15:28











                          10














                          Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.



                          Function.prototype.delay = function(ms /*[, arg...]*/) 
                          var fn = this,
                          args = Array.prototype.slice.call(arguments, 1);

                          return window.setTimeout(function()
                          return fn.apply(fn, args);
                          , ms);
                          ;


                          And here's how you would use it:



                          var startPlayback = function(track) 
                          Player.play(track);
                          ;
                          startPlayback(someTrack);


                          Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:



                          startPlayback.delay(5000, someTrack);
                          // Keep going, do other things


                          When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.

                          This is a type of currying, or function decoration.



                          Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readiblity of your code.






                          share|improve this answer




















                          • 1





                            It should be noted that extending language or host objects is generally considered a bad thing as they are part of the global namespace

                            – Jon Cooke
                            May 29 '14 at 3:10















                          10














                          Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.



                          Function.prototype.delay = function(ms /*[, arg...]*/) 
                          var fn = this,
                          args = Array.prototype.slice.call(arguments, 1);

                          return window.setTimeout(function()
                          return fn.apply(fn, args);
                          , ms);
                          ;


                          And here's how you would use it:



                          var startPlayback = function(track) 
                          Player.play(track);
                          ;
                          startPlayback(someTrack);


                          Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:



                          startPlayback.delay(5000, someTrack);
                          // Keep going, do other things


                          When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.

                          This is a type of currying, or function decoration.



                          Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readiblity of your code.






                          share|improve this answer




















                          • 1





                            It should be noted that extending language or host objects is generally considered a bad thing as they are part of the global namespace

                            – Jon Cooke
                            May 29 '14 at 3:10













                          10












                          10








                          10







                          Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.



                          Function.prototype.delay = function(ms /*[, arg...]*/) 
                          var fn = this,
                          args = Array.prototype.slice.call(arguments, 1);

                          return window.setTimeout(function()
                          return fn.apply(fn, args);
                          , ms);
                          ;


                          And here's how you would use it:



                          var startPlayback = function(track) 
                          Player.play(track);
                          ;
                          startPlayback(someTrack);


                          Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:



                          startPlayback.delay(5000, someTrack);
                          // Keep going, do other things


                          When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.

                          This is a type of currying, or function decoration.



                          Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readiblity of your code.






                          share|improve this answer















                          Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.



                          Function.prototype.delay = function(ms /*[, arg...]*/) 
                          var fn = this,
                          args = Array.prototype.slice.call(arguments, 1);

                          return window.setTimeout(function()
                          return fn.apply(fn, args);
                          , ms);
                          ;


                          And here's how you would use it:



                          var startPlayback = function(track) 
                          Player.play(track);
                          ;
                          startPlayback(someTrack);


                          Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:



                          startPlayback.delay(5000, someTrack);
                          // Keep going, do other things


                          When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.

                          This is a type of currying, or function decoration.



                          Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readiblity of your code.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          answered Nov 7 '10 at 19:04


























                          community wiki





                          adamJLev








                          • 1





                            It should be noted that extending language or host objects is generally considered a bad thing as they are part of the global namespace

                            – Jon Cooke
                            May 29 '14 at 3:10












                          • 1





                            It should be noted that extending language or host objects is generally considered a bad thing as they are part of the global namespace

                            – Jon Cooke
                            May 29 '14 at 3:10







                          1




                          1





                          It should be noted that extending language or host objects is generally considered a bad thing as they are part of the global namespace

                          – Jon Cooke
                          May 29 '14 at 3:10





                          It should be noted that extending language or host objects is generally considered a bad thing as they are part of the global namespace

                          – Jon Cooke
                          May 29 '14 at 3:10











                          5














                          Functions containing no free variables are called pure functions.



                          Functions containing one or more free variables are called closures.



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


                          var foo = "bar"

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



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






                          share|improve this answer

























                          • Why is this minused? It is actually much more "on the right track" with that distinction into free variables and bound variables, and pure/closed functions and impure/open functions, than most of the other clueless answers in here :P (discounting for confusing closures with functions being closed).

                            – SasQ
                            Apr 27 '16 at 2:43












                          • I have no Idea, really. This is why StackOverflow sucks. Just look at the source of my Answer. Who could argue with that?

                            – soundyogi
                            Apr 27 '16 at 13:22















                          5














                          Functions containing no free variables are called pure functions.



                          Functions containing one or more free variables are called closures.



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


                          var foo = "bar"

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



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






                          share|improve this answer

























                          • Why is this minused? It is actually much more "on the right track" with that distinction into free variables and bound variables, and pure/closed functions and impure/open functions, than most of the other clueless answers in here :P (discounting for confusing closures with functions being closed).

                            – SasQ
                            Apr 27 '16 at 2:43












                          • I have no Idea, really. This is why StackOverflow sucks. Just look at the source of my Answer. Who could argue with that?

                            – soundyogi
                            Apr 27 '16 at 13:22













                          5












                          5








                          5







                          Functions containing no free variables are called pure functions.



                          Functions containing one or more free variables are called closures.



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


                          var foo = "bar"

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



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






                          share|improve this answer















                          Functions containing no free variables are called pure functions.



                          Functions containing one or more free variables are called closures.



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


                          var foo = "bar"

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



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







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          answered Feb 7 '16 at 13:38


























                          community wiki





                          soundyogi













                          • Why is this minused? It is actually much more "on the right track" with that distinction into free variables and bound variables, and pure/closed functions and impure/open functions, than most of the other clueless answers in here :P (discounting for confusing closures with functions being closed).

                            – SasQ
                            Apr 27 '16 at 2:43












                          • I have no Idea, really. This is why StackOverflow sucks. Just look at the source of my Answer. Who could argue with that?

                            – soundyogi
                            Apr 27 '16 at 13:22

















                          • Why is this minused? It is actually much more "on the right track" with that distinction into free variables and bound variables, and pure/closed functions and impure/open functions, than most of the other clueless answers in here :P (discounting for confusing closures with functions being closed).

                            – SasQ
                            Apr 27 '16 at 2:43












                          • I have no Idea, really. This is why StackOverflow sucks. Just look at the source of my Answer. Who could argue with that?

                            – soundyogi
                            Apr 27 '16 at 13:22
















                          Why is this minused? It is actually much more "on the right track" with that distinction into free variables and bound variables, and pure/closed functions and impure/open functions, than most of the other clueless answers in here :P (discounting for confusing closures with functions being closed).

                          – SasQ
                          Apr 27 '16 at 2:43






                          Why is this minused? It is actually much more "on the right track" with that distinction into free variables and bound variables, and pure/closed functions and impure/open functions, than most of the other clueless answers in here :P (discounting for confusing closures with functions being closed).

                          – SasQ
                          Apr 27 '16 at 2:43














                          I have no Idea, really. This is why StackOverflow sucks. Just look at the source of my Answer. Who could argue with that?

                          – soundyogi
                          Apr 27 '16 at 13:22





                          I have no Idea, really. This is why StackOverflow sucks. Just look at the source of my Answer. Who could argue with that?

                          – soundyogi
                          Apr 27 '16 at 13:22











                          5














                          tl;dr



                          A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.



                          In depth Wikipedia style explanation



                          According to Wikipedia, a closure is:




                          Techniques for implementing lexically scoped name binding in languages with first-class functions.




                          What does that mean? Lets look into some definitions.



                          I will explain closures and other related definitions by using this example:






                          function startAt(x) 
                          return function (y)
                          return x + y;



                          var closure1 = startAt(1);
                          var closure2 = startAt(5);

                          console.log(closure1(3)); // 4 (x == 1, y == 3)
                          console.log(closure2(3)); // 8 (x == 5, y == 3)





                          First-class functions



                          Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.



                          In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).



                          Name binding



                          Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.



                          In the example above:



                          • In the inner anonymous function's scope, y is bound to 3.

                          • In startAt's scope, x is bound to 1 or 5 (depending on the closure).

                          Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.



                          Lexical scoping



                          As Wikipedia says, the scope:




                          Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.




                          There are two techniques:



                          • Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.

                          • Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.

                          For more explanation, check out this question and take a look at Wikipedia.



                          In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.



                          Wrapping (closuring) up



                          In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.



                          Now you should understand closures and how they behave, which is a fundamental part of JavaScript.



                          Currying



                          Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.






                          share|improve this answer





























                            5














                            tl;dr



                            A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.



                            In depth Wikipedia style explanation



                            According to Wikipedia, a closure is:




                            Techniques for implementing lexically scoped name binding in languages with first-class functions.




                            What does that mean? Lets look into some definitions.



                            I will explain closures and other related definitions by using this example:






                            function startAt(x) 
                            return function (y)
                            return x + y;



                            var closure1 = startAt(1);
                            var closure2 = startAt(5);

                            console.log(closure1(3)); // 4 (x == 1, y == 3)
                            console.log(closure2(3)); // 8 (x == 5, y == 3)





                            First-class functions



                            Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.



                            In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).



                            Name binding



                            Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.



                            In the example above:



                            • In the inner anonymous function's scope, y is bound to 3.

                            • In startAt's scope, x is bound to 1 or 5 (depending on the closure).

                            Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.



                            Lexical scoping



                            As Wikipedia says, the scope:




                            Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.




                            There are two techniques:



                            • Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.

                            • Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.

                            For more explanation, check out this question and take a look at Wikipedia.



                            In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.



                            Wrapping (closuring) up



                            In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.



                            Now you should understand closures and how they behave, which is a fundamental part of JavaScript.



                            Currying



                            Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.






                            share|improve this answer



























                              5












                              5








                              5







                              tl;dr



                              A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.



                              In depth Wikipedia style explanation



                              According to Wikipedia, a closure is:




                              Techniques for implementing lexically scoped name binding in languages with first-class functions.




                              What does that mean? Lets look into some definitions.



                              I will explain closures and other related definitions by using this example:






                              function startAt(x) 
                              return function (y)
                              return x + y;



                              var closure1 = startAt(1);
                              var closure2 = startAt(5);

                              console.log(closure1(3)); // 4 (x == 1, y == 3)
                              console.log(closure2(3)); // 8 (x == 5, y == 3)





                              First-class functions



                              Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.



                              In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).



                              Name binding



                              Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.



                              In the example above:



                              • In the inner anonymous function's scope, y is bound to 3.

                              • In startAt's scope, x is bound to 1 or 5 (depending on the closure).

                              Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.



                              Lexical scoping



                              As Wikipedia says, the scope:




                              Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.




                              There are two techniques:



                              • Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.

                              • Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.

                              For more explanation, check out this question and take a look at Wikipedia.



                              In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.



                              Wrapping (closuring) up



                              In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.



                              Now you should understand closures and how they behave, which is a fundamental part of JavaScript.



                              Currying



                              Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.






                              share|improve this answer















                              tl;dr



                              A closure is a function and its scope assigned to (or used as) a variable. Thus, the name closure: the scope and the function is enclosed and used just like any other entity.



                              In depth Wikipedia style explanation



                              According to Wikipedia, a closure is:




                              Techniques for implementing lexically scoped name binding in languages with first-class functions.




                              What does that mean? Lets look into some definitions.



                              I will explain closures and other related definitions by using this example:






                              function startAt(x) 
                              return function (y)
                              return x + y;



                              var closure1 = startAt(1);
                              var closure2 = startAt(5);

                              console.log(closure1(3)); // 4 (x == 1, y == 3)
                              console.log(closure2(3)); // 8 (x == 5, y == 3)





                              First-class functions



                              Basically that means we can use functions just like any other entity. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are first-class citizens, hence the name: first-class functions.



                              In the example above, startAt returns an (anonymous) function which function get assigned to closure1 and closure2. So as you see JavaScript treats functions just like any other entities (first-class citizens).



                              Name binding



                              Name binding is about finding out what data a variable (identifier) references. The scope is really important here, as that is the thing that will determine how a binding is resolved.



                              In the example above:



                              • In the inner anonymous function's scope, y is bound to 3.

                              • In startAt's scope, x is bound to 1 or 5 (depending on the closure).

                              Inside the anonymous function's scope, x is not bound to any value, so it needs to be resolved in an upper (startAt's) scope.



                              Lexical scoping



                              As Wikipedia says, the scope:




                              Is the region of a computer program where the binding is valid: where the name can be used to refer to the entity.




                              There are two techniques:



                              • Lexical (static) scoping: A variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on.

                              • Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.

                              For more explanation, check out this question and take a look at Wikipedia.



                              In the example above, we can see that JavaScript is lexically scoped, because when x is resolved, the binding is searched in the upper (startAt's) scope, based on the source code (the anonymous function that looks for x is defined inside startAt) and not based on the call stack, the way (the scope where) the function was called.



                              Wrapping (closuring) up



                              In our example, when we call startAt, it will return a (first-class) function that will be assigned to closure1 and closure2 thus a closure is created, because the passed variables 1 and 5 will be saved within startAt's scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via closure1 and closure2 with the same argument (3), the value of y will be found immediately (as that is the parameter of that function), but x is not bound in the scope of the anonymous function, so the resolution continues in the (lexically) upper function scope (that was saved in the closure) where x is found to be bound to either 1 or 5. Now we know everything for the summation so the result can be returned, then printed.



                              Now you should understand closures and how they behave, which is a fundamental part of JavaScript.



                              Currying



                              Oh, and you also learned what currying is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.






                              function startAt(x) 
                              return function (y)
                              return x + y;



                              var closure1 = startAt(1);
                              var closure2 = startAt(5);

                              console.log(closure1(3)); // 4 (x == 1, y == 3)
                              console.log(closure2(3)); // 8 (x == 5, y == 3)





                              function startAt(x) 
                              return function (y)
                              return x + y;



                              var closure1 = startAt(1);
                              var closure2 = startAt(5);

                              console.log(closure1(3)); // 4 (x == 1, y == 3)
                              console.log(closure2(3)); // 8 (x == 5, y == 3)






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              answered Jul 4 '17 at 23:43


























                              community wiki





                              totymedli






















                                  4














                                  In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.



                                  def n_times(a_thing)
                                  return lambda a_thing * n
                                  end


                                  in the above code, lambda(|n| a_thing * n} is the closure because a_thing is referred by the lambda (an anonymous function creator).



                                  Now, if you put the resulting anonymous function in a function variable.



                                  foo = n_times(4)


                                  foo will break the normal scoping rule and start using 4 internally.



                                  foo.call(3)


                                  returns 12.






                                  share|improve this answer



























                                    4














                                    In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.



                                    def n_times(a_thing)
                                    return lambda a_thing * n
                                    end


                                    in the above code, lambda(|n| a_thing * n} is the closure because a_thing is referred by the lambda (an anonymous function creator).



                                    Now, if you put the resulting anonymous function in a function variable.



                                    foo = n_times(4)


                                    foo will break the normal scoping rule and start using 4 internally.



                                    foo.call(3)


                                    returns 12.






                                    share|improve this answer

























                                      4












                                      4








                                      4







                                      In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.



                                      def n_times(a_thing)
                                      return lambda a_thing * n
                                      end


                                      in the above code, lambda(|n| a_thing * n} is the closure because a_thing is referred by the lambda (an anonymous function creator).



                                      Now, if you put the resulting anonymous function in a function variable.



                                      foo = n_times(4)


                                      foo will break the normal scoping rule and start using 4 internally.



                                      foo.call(3)


                                      returns 12.






                                      share|improve this answer













                                      In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.



                                      def n_times(a_thing)
                                      return lambda a_thing * n
                                      end


                                      in the above code, lambda(|n| a_thing * n} is the closure because a_thing is referred by the lambda (an anonymous function creator).



                                      Now, if you put the resulting anonymous function in a function variable.



                                      foo = n_times(4)


                                      foo will break the normal scoping rule and start using 4 internally.



                                      foo.call(3)


                                      returns 12.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 31 '08 at 5:31









                                      Eugene YokotaEugene Yokota

                                      73.9k39182278




                                      73.9k39182278





















                                          2














                                          In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas Closure = Function pointer + Stack frame.



                                          .






                                          share|improve this answer





























                                            2














                                            In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas Closure = Function pointer + Stack frame.



                                            .






                                            share|improve this answer



























                                              2












                                              2








                                              2







                                              In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas Closure = Function pointer + Stack frame.



                                              .






                                              share|improve this answer















                                              In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas Closure = Function pointer + Stack frame.



                                              .







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              answered Sep 7 '13 at 13:50


























                                              community wiki





                                              RoboAlex






















                                                  0














                                                  Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.



                                                  local old_dofile = dofile

                                                  function dofile( filename )
                                                  if filename == nil then
                                                  error( 'Can not use default of stdin.' )
                                                  end

                                                  old_dofile( filename )
                                                  end


                                                  The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.






                                                  share|improve this answer





























                                                    0














                                                    Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.



                                                    local old_dofile = dofile

                                                    function dofile( filename )
                                                    if filename == nil then
                                                    error( 'Can not use default of stdin.' )
                                                    end

                                                    old_dofile( filename )
                                                    end


                                                    The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.






                                                    share|improve this answer



























                                                      0












                                                      0








                                                      0







                                                      Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.



                                                      local old_dofile = dofile

                                                      function dofile( filename )
                                                      if filename == nil then
                                                      error( 'Can not use default of stdin.' )
                                                      end

                                                      old_dofile( filename )
                                                      end


                                                      The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.






                                                      share|improve this answer















                                                      Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.



                                                      local old_dofile = dofile

                                                      function dofile( filename )
                                                      if filename == nil then
                                                      error( 'Can not use default of stdin.' )
                                                      end

                                                      old_dofile( filename )
                                                      end


                                                      The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      answered May 12 '11 at 5:57


























                                                      community wiki





                                                      Nigel Atkinson






















                                                          0














                                                          From Lua.org:




                                                          When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.







                                                          share|improve this answer





























                                                            0














                                                            From Lua.org:




                                                            When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.







                                                            share|improve this answer



























                                                              0












                                                              0








                                                              0







                                                              From Lua.org:




                                                              When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.







                                                              share|improve this answer















                                                              From Lua.org:




                                                              When a function is written enclosed in another function, it has full access to local variables from the enclosing function; this feature is called lexical scoping. Although that may sound obvious, it is not. Lexical scoping, plus first-class functions, is a powerful concept in a programming language, but few languages support that concept.








                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              answered Dec 30 '15 at 23:06


























                                                              community wiki





                                                              user5731811






















                                                                  0














                                                                  If you are from the Java world, you can compare a closure with a member function of a class. Look at this example



                                                                  var f=function()
                                                                  var a=7;
                                                                  var g=function()
                                                                  return a;

                                                                  return g;



                                                                  The function g is a closure: g closes a in. So g can be compared with a member function, a can be compared with a class field, and the function f with a class.






                                                                  share|improve this answer





























                                                                    0














                                                                    If you are from the Java world, you can compare a closure with a member function of a class. Look at this example



                                                                    var f=function()
                                                                    var a=7;
                                                                    var g=function()
                                                                    return a;

                                                                    return g;



                                                                    The function g is a closure: g closes a in. So g can be compared with a member function, a can be compared with a class field, and the function f with a class.






                                                                    share|improve this answer



























                                                                      0












                                                                      0








                                                                      0







                                                                      If you are from the Java world, you can compare a closure with a member function of a class. Look at this example



                                                                      var f=function()
                                                                      var a=7;
                                                                      var g=function()
                                                                      return a;

                                                                      return g;



                                                                      The function g is a closure: g closes a in. So g can be compared with a member function, a can be compared with a class field, and the function f with a class.






                                                                      share|improve this answer















                                                                      If you are from the Java world, you can compare a closure with a member function of a class. Look at this example



                                                                      var f=function()
                                                                      var a=7;
                                                                      var g=function()
                                                                      return a;

                                                                      return g;



                                                                      The function g is a closure: g closes a in. So g can be compared with a member function, a can be compared with a class field, and the function f with a class.







                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited Apr 2 '16 at 19:35


























                                                                      community wiki





                                                                      3 revs
                                                                      ericj






















                                                                          0














                                                                          Closures
                                                                          Whenever we have a function defined inside another function, the inner function has access to the variables declared
                                                                          in the outer function. Closures are best explained with examples.
                                                                          In Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the
                                                                          outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term
                                                                          closure. The concept in itself is simple enough and fairly intuitive.



                                                                          Listing 2-18:
                                                                          function outerFunction(arg)
                                                                          var variableInOuterFunction = arg;

                                                                          function bar()
                                                                          console.log(variableInOuterFunction); // Access a variable from the outer scope

                                                                          // Call the local function to demonstrate that it has access to arg
                                                                          bar();

                                                                          outerFunction('hello closure!'); // logs hello closure!


                                                                          source: http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf






                                                                          share|improve this answer





























                                                                            0














                                                                            Closures
                                                                            Whenever we have a function defined inside another function, the inner function has access to the variables declared
                                                                            in the outer function. Closures are best explained with examples.
                                                                            In Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the
                                                                            outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term
                                                                            closure. The concept in itself is simple enough and fairly intuitive.



                                                                            Listing 2-18:
                                                                            function outerFunction(arg)
                                                                            var variableInOuterFunction = arg;

                                                                            function bar()
                                                                            console.log(variableInOuterFunction); // Access a variable from the outer scope

                                                                            // Call the local function to demonstrate that it has access to arg
                                                                            bar();

                                                                            outerFunction('hello closure!'); // logs hello closure!


                                                                            source: http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf






                                                                            share|improve this answer



























                                                                              0












                                                                              0








                                                                              0







                                                                              Closures
                                                                              Whenever we have a function defined inside another function, the inner function has access to the variables declared
                                                                              in the outer function. Closures are best explained with examples.
                                                                              In Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the
                                                                              outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term
                                                                              closure. The concept in itself is simple enough and fairly intuitive.



                                                                              Listing 2-18:
                                                                              function outerFunction(arg)
                                                                              var variableInOuterFunction = arg;

                                                                              function bar()
                                                                              console.log(variableInOuterFunction); // Access a variable from the outer scope

                                                                              // Call the local function to demonstrate that it has access to arg
                                                                              bar();

                                                                              outerFunction('hello closure!'); // logs hello closure!


                                                                              source: http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf






                                                                              share|improve this answer















                                                                              Closures
                                                                              Whenever we have a function defined inside another function, the inner function has access to the variables declared
                                                                              in the outer function. Closures are best explained with examples.
                                                                              In Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the
                                                                              outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term
                                                                              closure. The concept in itself is simple enough and fairly intuitive.



                                                                              Listing 2-18:
                                                                              function outerFunction(arg)
                                                                              var variableInOuterFunction = arg;

                                                                              function bar()
                                                                              console.log(variableInOuterFunction); // Access a variable from the outer scope

                                                                              // Call the local function to demonstrate that it has access to arg
                                                                              bar();

                                                                              outerFunction('hello closure!'); // logs hello closure!


                                                                              source: http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf







                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              answered Aug 3 '17 at 9:15


























                                                                              community wiki





                                                                              shohan






















                                                                                  0














                                                                                  Please have a look below code to understand closure in more deep:



                                                                                   for(var i=0; i< 5; i++) 
                                                                                  setTimeout(function()
                                                                                  console.log(i);
                                                                                  , 1000);



                                                                                  Here what will be output? 0,1,2,3,4 not that will be 5,5,5,5,5 because of closure



                                                                                  So how it will solve? Answer is below:



                                                                                   for(var i=0; i< 5; i++)
                                                                                  (function(j) //using IIFE
                                                                                  setTimeout(function()
                                                                                  console.log(j);
                                                                                  ,1000);
                                                                                  )(i);



                                                                                  Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute setTimeout function five time and print 5,5,5,5,5



                                                                                  Here how it solve using IIFE i.e Immediate Invoking Function Expression



                                                                                   (function(j) //i is passed here 
                                                                                  setTimeout(function()
                                                                                  console.log(j);
                                                                                  ,1000);
                                                                                  )(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4


                                                                                  For more, please understand execution context to understand closure.




                                                                                  • There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked



                                                                                     for(let i=0; i< 5; i++) 
                                                                                    setTimeout(function()
                                                                                    console.log(i);
                                                                                    ,1000);


                                                                                    Output: 0,1,2,3,4


                                                                                  => More explanation:



                                                                                  In memory, when for loop execute picture make like below:



                                                                                  Loop 1)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 2)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 3)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 4)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 5)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside setTimeout out five time it prints 5,5,5,5,5



                                                                                  so to resolve this use IIFE as explain above.






                                                                                  share|improve this answer

























                                                                                  • thanks for your answer. it would be more readable if you separated code from explanation. (don't indent lines that are not code)

                                                                                    – eMBee
                                                                                    Dec 15 '18 at 16:07















                                                                                  0














                                                                                  Please have a look below code to understand closure in more deep:



                                                                                   for(var i=0; i< 5; i++) 
                                                                                  setTimeout(function()
                                                                                  console.log(i);
                                                                                  , 1000);



                                                                                  Here what will be output? 0,1,2,3,4 not that will be 5,5,5,5,5 because of closure



                                                                                  So how it will solve? Answer is below:



                                                                                   for(var i=0; i< 5; i++)
                                                                                  (function(j) //using IIFE
                                                                                  setTimeout(function()
                                                                                  console.log(j);
                                                                                  ,1000);
                                                                                  )(i);



                                                                                  Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute setTimeout function five time and print 5,5,5,5,5



                                                                                  Here how it solve using IIFE i.e Immediate Invoking Function Expression



                                                                                   (function(j) //i is passed here 
                                                                                  setTimeout(function()
                                                                                  console.log(j);
                                                                                  ,1000);
                                                                                  )(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4


                                                                                  For more, please understand execution context to understand closure.




                                                                                  • There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked



                                                                                     for(let i=0; i< 5; i++) 
                                                                                    setTimeout(function()
                                                                                    console.log(i);
                                                                                    ,1000);


                                                                                    Output: 0,1,2,3,4


                                                                                  => More explanation:



                                                                                  In memory, when for loop execute picture make like below:



                                                                                  Loop 1)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 2)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 3)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 4)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 5)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside setTimeout out five time it prints 5,5,5,5,5



                                                                                  so to resolve this use IIFE as explain above.






                                                                                  share|improve this answer

























                                                                                  • thanks for your answer. it would be more readable if you separated code from explanation. (don't indent lines that are not code)

                                                                                    – eMBee
                                                                                    Dec 15 '18 at 16:07













                                                                                  0












                                                                                  0








                                                                                  0







                                                                                  Please have a look below code to understand closure in more deep:



                                                                                   for(var i=0; i< 5; i++) 
                                                                                  setTimeout(function()
                                                                                  console.log(i);
                                                                                  , 1000);



                                                                                  Here what will be output? 0,1,2,3,4 not that will be 5,5,5,5,5 because of closure



                                                                                  So how it will solve? Answer is below:



                                                                                   for(var i=0; i< 5; i++)
                                                                                  (function(j) //using IIFE
                                                                                  setTimeout(function()
                                                                                  console.log(j);
                                                                                  ,1000);
                                                                                  )(i);



                                                                                  Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute setTimeout function five time and print 5,5,5,5,5



                                                                                  Here how it solve using IIFE i.e Immediate Invoking Function Expression



                                                                                   (function(j) //i is passed here 
                                                                                  setTimeout(function()
                                                                                  console.log(j);
                                                                                  ,1000);
                                                                                  )(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4


                                                                                  For more, please understand execution context to understand closure.




                                                                                  • There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked



                                                                                     for(let i=0; i< 5; i++) 
                                                                                    setTimeout(function()
                                                                                    console.log(i);
                                                                                    ,1000);


                                                                                    Output: 0,1,2,3,4


                                                                                  => More explanation:



                                                                                  In memory, when for loop execute picture make like below:



                                                                                  Loop 1)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 2)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 3)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 4)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 5)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside setTimeout out five time it prints 5,5,5,5,5



                                                                                  so to resolve this use IIFE as explain above.






                                                                                  share|improve this answer















                                                                                  Please have a look below code to understand closure in more deep:



                                                                                   for(var i=0; i< 5; i++) 
                                                                                  setTimeout(function()
                                                                                  console.log(i);
                                                                                  , 1000);



                                                                                  Here what will be output? 0,1,2,3,4 not that will be 5,5,5,5,5 because of closure



                                                                                  So how it will solve? Answer is below:



                                                                                   for(var i=0; i< 5; i++)
                                                                                  (function(j) //using IIFE
                                                                                  setTimeout(function()
                                                                                  console.log(j);
                                                                                  ,1000);
                                                                                  )(i);



                                                                                  Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute setTimeout function five time and print 5,5,5,5,5



                                                                                  Here how it solve using IIFE i.e Immediate Invoking Function Expression



                                                                                   (function(j) //i is passed here 
                                                                                  setTimeout(function()
                                                                                  console.log(j);
                                                                                  ,1000);
                                                                                  )(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4


                                                                                  For more, please understand execution context to understand closure.




                                                                                  • There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked



                                                                                     for(let i=0; i< 5; i++) 
                                                                                    setTimeout(function()
                                                                                    console.log(i);
                                                                                    ,1000);


                                                                                    Output: 0,1,2,3,4


                                                                                  => More explanation:



                                                                                  In memory, when for loop execute picture make like below:



                                                                                  Loop 1)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 2)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 3)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 4)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Loop 5)



                                                                                   setTimeout(function()
                                                                                  console.log(i);
                                                                                  ,1000);


                                                                                  Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside setTimeout out five time it prints 5,5,5,5,5



                                                                                  so to resolve this use IIFE as explain above.







                                                                                  share|improve this answer














                                                                                  share|improve this answer



                                                                                  share|improve this answer








                                                                                  edited Dec 15 '18 at 16:14


























                                                                                  community wiki





                                                                                  3 revs, 2 users 74%
                                                                                  arun













                                                                                  • thanks for your answer. it would be more readable if you separated code from explanation. (don't indent lines that are not code)

                                                                                    – eMBee
                                                                                    Dec 15 '18 at 16:07

















                                                                                  • thanks for your answer. it would be more readable if you separated code from explanation. (don't indent lines that are not code)

                                                                                    – eMBee
                                                                                    Dec 15 '18 at 16:07
















                                                                                  thanks for your answer. it would be more readable if you separated code from explanation. (don't indent lines that are not code)

                                                                                  – eMBee
                                                                                  Dec 15 '18 at 16:07





                                                                                  thanks for your answer. it would be more readable if you separated code from explanation. (don't indent lines that are not code)

                                                                                  – eMBee
                                                                                  Dec 15 '18 at 16:07

















                                                                                  draft saved

                                                                                  draft discarded
















































                                                                                  Thanks for contributing an answer to Stack Overflow!


                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                  But avoid


                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                                                  To learn more, see our tips on writing great answers.




                                                                                  draft saved


                                                                                  draft discarded














                                                                                  StackExchange.ready(
                                                                                  function ()
                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36636%2fwhat-is-a-closure%23new-answer', 'question_page');

                                                                                  );

                                                                                  Post as a guest















                                                                                  Required, but never shown





















































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown

































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown







                                                                                  Popular posts from this blog

                                                                                  Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                                                                  Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                                                                  Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved