73

I understand what closures are, but I am having some trouble grokking exactly what the term closure refers to. I have seen the term used in many websites, but rarely do they agree on the actual definition of it.

  • Is it the variables that are kept on the stack frame?
  • Is it the function that is being returned?
  • Is it the scope of the outer function?
  • Is it the scope of the inner (returned) function?
  • Is it maybe the concept of keeping the variables on the stack-frame after returning the function?

Can someone tell me exactly to what closure refers to?

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • 8
    +1 because you ask handy questions – alex Nov 27 '09 at 03:55
  • After looking through 1/2 dozen explanations .. this one looks pretty good for breaking down the main considerations http://www.sitepoint.com/javascript-closures-demystified/ – Gene Bo Jul 01 '15 at 21:03

8 Answers8

45

From JavaScript Closures

Two one-sentence summaries:

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

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

A very good article on closures

Javascript Closures

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

The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodies of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s). A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

A good example over here

JavaScript, time to grok closures

Robusto
  • 31,447
  • 8
  • 56
  • 77
rahul
  • 184,426
  • 49
  • 232
  • 263
  • I have written a set of articles on this with graphical explanations. Read chapters-4 and 5 here: https://rahuldotout.wordpress.com/2011/05/15/professional-javascript-part-4-scopes-and-scope-chain/ – rahulmohan Jun 13 '11 at 05:40
  • `A closure is the local variables for a function - kept alive after the function has returned, or` it should be variable only? or function? or both? because on the official document they said inner function as closure. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – Asif Mushtaq Jul 07 '18 at 05:08
6

It's a function that "holds" a reference or references to something in another scope. For example:

var myArrayOfFunctions = [];

for(var i = 0; i<3: i++)
{
    //Note how the function being defined uses i, 
    //where i lives in the parent's scope, this creates a closure
    myArrayOfFunctions[i] = function(a) { return a + i;}    
}

myArrayOfFunctions[0](5);   //Prints 8 WTF!
myArrayOfFunctions[1](5);   //8 again
myArrayOfFunctions[2](5);   //Well, this 8 was expected

This happens because when the functions are "created", they do not copy the value of i, they hold a reference to i, so when we call the functions they use the current value of i which is 3.

Here is a graphical explanation.

Daniel Rodriguez
  • 1,443
  • 12
  • 19
4

For me, the closures in JS allows you to do the following.
"a" remains available in the inner function when added to "b" although it is declared outside.

function adder(a){
  return function(b){
    return a + b;
  };
}
var add5 = adder(5);
alert( add5(10) );

For an extreme usage of JS closures, you can have a look at the source code of the PURE library (a JS templating engine)

Mic
  • 24,812
  • 9
  • 57
  • 70
2

As far as I can tell, a closure is a function defined within another function that outlives the parent function's scope. A common example is callbacks:

function delay_message(msg)
{
     setTimeout(function closure() { alert(msg); }, 1000);
}

In this case, the above function closure is defined within the body of delay_message, but the function definition -- as well as the parent function's variable msg -- outlive the scope of the delay_message function call.

intgr
  • 19,834
  • 5
  • 59
  • 69
  • so you're saying that the closure is the inner function ? – Andreas Grech Nov 26 '09 at 20:41
  • A "closure" is the combination of a function and its state. I.e., inner function that is bound to a set of local variables from the outer function. – intgr Nov 27 '09 at 02:59
  • The inner function (`function closure`) is created at parse time, but at that point there is no closure. A closure is created as `function delay_message` executes and binds its state to `function closure`. – intgr Nov 27 '09 at 03:02
  • An anonymous function is not a closure. Please do not keep spreading this misnomer. – Mike Axiak Sep 15 '10 at 23:13
2

Consider the following code that creates a closure with variables a and b

closure=(function(){ 

    var a=3
    var b=5 

return  function(operation){ 
          return operation(a,b)
      }
 }())


// The variables a and b are now part of the closure (They are retained even after the outer function returns)


closure(function(x,y){return x+y})  // outputs 8

closure(function(x,y){return x*y}) // outputs 15`

This particular closure can now take any function that operates on the variables a and b

sarath joseph
  • 2,533
  • 2
  • 20
  • 23
1

Essentially a closure is a function body closed over its identifiers (variables) within its local environment.

Mark Ursino
  • 31,209
  • 11
  • 51
  • 83
1

A closure is a function value created from a nested function declaration or function expression (i.e. lambda expression) whose body contains one or more references to variables declared in an outer (but not global) scope.

Theodore Norvell
  • 15,366
  • 6
  • 31
  • 45
0

Closure means a function(outer function) containing another function(inner function).

Closure is used to protect the data.

the use of closer is demostrated in the video link provide below:

https://www.youtube.com/watch?v=w1s9PgtEoJs

Abhishek-Saini
  • 733
  • 7
  • 11