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

[{'answer_id': 36639, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 7, 'selected': False, 'text': '<p>I\'ll give an example (in JavaScript):</p>\n<pre class="lang-js prettyprint-override"><code>function makeCounter () {\n  var count = 0;\n  return function () {\n    count += 1;\n    return count;\n  }\n}\n\nvar x = makeCounter();\nx(); returns 1\nx(); returns 2\n...etc...\n</code></pre>\n<p>What this function, <code>makeCounter</code>, does is it returns a function, which we\'ve called <code>x</code>, that will count up by one each time it\'s called. Since we\'re not providing any parameters to <code>x</code>, 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 &quot;hidden&quot; value is what is called a closure.</p>\n<p>Here is my currying example again:</p>\n<pre class="lang-js prettyprint-override"><code>function add (a) {\n  return function (b) {\n    return a + b;\n  }\n}\n\nvar add3 = add(3);\n    \nadd3(4); returns 7\n</code></pre>\n<p>What you can see is that when you call <code>add</code> with the parameter <code>a</code> (which is 3), that value is contained in the closure of the returned function that we\'re defining to be <code>add3</code>. That way, when we call <code>add3</code>, it knows where to find the <code>a</code> value to perform the addition.</p>\n'}, {'answer_id': 36641, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 5, 'selected': False, 'text': '<p>A closure is a function that can reference state in another function. For example, in Python, this uses the closure "inner":</p>\n\n<pre class="lang-py prettyprint-override"><code>def outer (a):\n    b = "variable in outer()"\n    def inner (c):\n        print a, b, c\n    return inner\n\n# Now the return value from outer() can be saved for later\nfunc = outer ("test")\nfunc (1) # prints "test variable in outer() 1\n</code></pre>\n'}, {'answer_id': 36652, 'author': 'Eugene Yokota', 'author_id': 3827, 'author_profile': 'https://Stackoverflow.com/users/3827', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>def n_times(a_thing)\n  return lambda{|n| a_thing * n}\nend\n</code></pre>\n\n<p>in the above code, <code>lambda(|n| a_thing * n}</code> is the closure because <code>a_thing</code> is referred by the lambda (an anonymous function creator).</p>\n\n<p>Now, if you put the resulting anonymous function in a function variable.</p>\n\n<pre><code>foo = n_times(4)\n</code></pre>\n\n<p>foo will break the normal scoping rule and start using 4 internally.</p>\n\n<pre><code>foo.call(3)\n</code></pre>\n\n<p>returns 12.</p>\n'}, {'answer_id': 36699, 'author': 'Ben Childs', 'author_id': 2925, 'author_profile': 'https://Stackoverflow.com/users/2925', 'pm_score': 6, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/a/36639/370671">Kyle\'s answer</a> 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 (<code>count</code>) is available when the lambda function executes.</p>\n'}, {'answer_id': 36945, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 5, 'selected': False, 'text': "<p>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.</p>\n\n<p>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:</p>\n\n<pre><code>(define x 3)\n\n(define y 4)\n\n(+ x y) returns 7\n</code></pre>\n\n<p>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.</p>\n\n<p>However, in Scheme there are expressions that allow you to temporarily override the value of a symbol. Here's an example:</p>\n\n<pre><code>(define x 3)\n\n(define y 4)\n\n(let ((x 5))\n   (+ x y)) returns 9\n\nx returns 3\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>(define x 3)\n\n(define (plus-x y)\n  (+ x y))\n\n(let ((x 5))\n  (plus-x 4)) returns ?\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>(define x 3)\n\n(define (plus-x y)\n  (+ x y))\n\n(let ((x 5))\n  (plus-x 4)) returns 7\n</code></pre>\n\n<p>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.</p>\n"}, {'answer_id': 4119185, 'author': 'adamJLev', 'author_id': 26192, 'author_profile': 'https://Stackoverflow.com/users/26192', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.</p>\n\n<pre class="lang-js prettyprint-override"><code>Function.prototype.delay = function(ms /*[, arg...]*/) {\n  var fn = this,\n      args = Array.prototype.slice.call(arguments, 1);\n\n  return window.setTimeout(function() {\n      return fn.apply(fn, args);\n  }, ms);\n};\n</code></pre>\n\n<p>And here\'s how you would use it:</p>\n\n<pre class="lang-js prettyprint-override"><code>var startPlayback = function(track) {\n  Player.play(track);  \n};\nstartPlayback(someTrack);\n</code></pre>\n\n<p>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 <code>delay</code> and it\'s closure:</p>\n\n<pre class="lang-js prettyprint-override"><code>startPlayback.delay(5000, someTrack);\n// Keep going, do other things\n</code></pre>\n\n<p>When you call <code>delay</code> with <code>5000</code>ms, the first snippet runs, and stores the passed in arguments in it\'s closure. Then 5 seconds later, when the <code>setTimeout</code> callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.<br>\nThis is a type of currying, or function decoration.</p>\n\n<p>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 readability of your code.</p>\n'}, {'answer_id': 5973885, 'author': 'Nigel Atkinson', 'author_id': 707446, 'author_profile': 'https://Stackoverflow.com/users/707446', 'pm_score': 0, 'selected': False, 'text': "<p>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.</p>\n\n<pre><code>local old_dofile = dofile\n\nfunction dofile( filename )\n  if filename == nil then\n    error( 'Can not use default of stdin.' )\n  end\n\n  old_dofile( filename )\nend\n</code></pre>\n\n<p>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'.</p>\n"}, {'answer_id': 7464475, 'author': 'superluminary', 'author_id': 687677, 'author_profile': 'https://Stackoverflow.com/users/687677', 'pm_score': 11, 'selected': True, 'text': '<h2>Variable scope</h2>\n<p>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.</p>\n<pre class="lang-js prettyprint-override"><code>function() {\n  var a = 1;\n  console.log(a); // works\n}    \nconsole.log(a); // fails\n</code></pre>\n<p>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.</p>\n<pre class="lang-js prettyprint-override"><code>var a = 1;\nfunction() {\n  console.log(a); // works\n}    \nconsole.log(a); // works\n</code></pre>\n<p>When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.</p>\n<p>This is how we normally expect things to work.</p>\n<h2>A closure is a persistent local variable scope</h2>\n<p>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.</p>\n<p>The scope object and all its local variables are tied to the function and will persist as long as that function persists.</p>\n<p>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.</p>\n<h2>For example</h2>\n<p>Here\'s a really simple example in JavaScript that illustrates the point:</p>\n<pre class="lang-js prettyprint-override"><code>outer = function() {\n  var a = 1;\n  var inner = function() {\n    console.log(a);\n  }\n  return inner; // this returns a function\n}\n\nvar fnc = outer(); // execute outer to get inner \nfnc();\n</code></pre>\n<p>Here I have defined a function within a function. The inner function gains access to all the outer function\'s local variables, including <code>a</code>. The variable <code>a</code> is in scope for the inner function.</p>\n<p>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 <code>fnc</code> so that it persists after <code>outer</code> has exited, <strong>all of the variables that were in scope when <code>inner</code> was defined also persist</strong>. The variable <code>a</code> has been closed over -- it is within a closure.</p>\n<p>Note that the variable <code>a</code> is totally private to <code>fnc</code>. This is a way of creating private variables in a functional programming language such as JavaScript.</p>\n<p>As you might be able to guess, when I call <code>fnc()</code> it prints the value of <code>a</code>, which is &quot;1&quot;.</p>\n<p>In a language without closure, the variable <code>a</code> would have been garbage collected and thrown away when the function <code>outer</code> exited. Calling fnc would have thrown an error because <code>a</code> no longer exists.</p>\n<p>In JavaScript, the variable <code>a</code> persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist.</p>\n<p><code>a</code> belongs to the scope of <code>outer</code>. The scope of <code>inner</code> has a parent pointer to the scope of <code>outer</code>. <code>fnc</code> is a variable which points to <code>inner</code>. <code>a</code> persists as long as <code>fnc</code> persists. <code>a</code> is within the closure.</p>\n<h2>Further reading (watching)</h2>\n<p>I made a <a href="https://www.youtube.com/watch?v=2cRjcXwsG0I" rel="noreferrer">YouTube video</a> looking at this code with some practical examples of usage.</p>\n'}, {'answer_id': 18673996, 'author': 'RoboAlex', 'author_id': 505406, 'author_profile': 'https://Stackoverflow.com/users/505406', 'pm_score': 2, 'selected': False, 'text': '<p>In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas <strong>Closure = Function pointer + Stack frame</strong>.</p>\n\n<p>.</p>\n'}, {'answer_id': 34538639, 'author': 'user5731811', 'author_id': 5731811, 'author_profile': 'https://Stackoverflow.com/users/5731811', 'pm_score': 0, 'selected': False, 'text': '<p>From <a href="http://www.lua.org/pil/6.1.html" rel="nofollow">Lua.org</a>:</p>\n\n<blockquote>\n  <p>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.</p>\n</blockquote>\n'}, {'answer_id': 35254177, 'author': 'soundyogi', 'author_id': 3293027, 'author_profile': 'https://Stackoverflow.com/users/3293027', 'pm_score': 4, 'selected': False, 'text': '<h2>Functions containing no free variables are called pure functions.</h2>\n<h2>Functions containing one or more free variables are called closures.</h2>\n<pre class="lang-js prettyprint-override"><code>var pure = function pure(x){\n  return x \n  // only own environment is used\n}\n\nvar foo = &quot;bar&quot;\n\nvar closure = function closure(){\n  return foo \n  // foo is a free variable from the outer environment\n}\n</code></pre>\n<p><sup>src: <a href="https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure" rel="noreferrer">https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure</a></sup></p>\n'}, {'answer_id': 36377697, 'author': 'ericj', 'author_id': 1065175, 'author_profile': 'https://Stackoverflow.com/users/1065175', 'pm_score': 0, 'selected': False, 'text': '<p>If you are from the Java world, you can compare a closure with a member function of a class. Look at this example</p>\n\n<pre><code>var f=function(){\n  var a=7;\n  var g=function(){\n    return a;\n  }\n  return g;\n}\n</code></pre>\n\n<p>The function <code>g</code> is a closure: <code>g</code> closes <code>a</code> in. So <code>g</code> can be compared with a member function, <code>a</code> can be compared with a class field, and the function <code>f</code> with a class.</p>\n'}, {'answer_id': 36879264, 'author': 'SasQ', 'author_id': 434562, 'author_profile': 'https://Stackoverflow.com/users/434562', 'pm_score': 7, 'selected': False, 'text': '<p>First of all, contrary to what most of the people here tell you, <strong>closure is <em>not</em> a function</strong>! So what <em>is</em> it?<br/>\nIt is a <em>set</em> of symbols defined in a function\'s &quot;surrounding context&quot; (known as its <em>environment</em>) 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).</p>\n<p>For example, when you have a JavaScript function:</p>\n<pre class="lang-js prettyprint-override"><code>function closed(x) {\n  return x + 3;\n}\n</code></pre>\n<p>it is a <em>closed expression</em> 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 <em>self-contained</em>.</p>\n<p>But if you have a function like this:</p>\n<pre class="lang-js prettyprint-override"><code>function open(x) {\n  return x*y + 3;\n}\n</code></pre>\n<p>it is an <em>open expression</em> because there are symbols in it which have not been defined in it. Namely, <code>y</code>. When looking at this function, we can\'t tell what <code>y</code> 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 <code>y</code> is supposed to mean in it. This <code>y</code> is called a <em>free variable</em>.</p>\n<p>This <code>y</code> begs for a definition, but this definition is not part of the function – it is defined somewhere else, in its &quot;surrounding context&quot; (also known as the <em>environment</em>). At least that\'s what we hope for :P</p>\n<p>For example, it could be defined globally:</p>\n<pre class="lang-js prettyprint-override"><code>var y = 7;\n\nfunction open(x) {\n  return x*y + 3;\n}\n</code></pre>\n<p>Or it could be defined in a function which wraps it:</p>\n<pre class="lang-js prettyprint-override"><code>var global = 2;\n\nfunction wrapper(y) {\n  var w = &quot;unused&quot;;\n\n  return function(x) {\n    return x*y + 3;\n  }\n}\n</code></pre>\n<p>The part of the environment which gives the free variables in an expression their meanings, is the <em>closure</em>. It is called this way, because it turns an <em>open</em> expression into a <em>closed</em> one, by supplying these missing definitions for all of its <em>free variables</em>, so that we could evaluate it.</p>\n<p>In the example above, the inner function (which we didn\'t give a name because we didn\'t need it) is an <em>open expression</em> because the variable <code>y</code> in it is <em>free</em> – its definition is outside the function, in the function which wraps it. The <em>environment</em> for that anonymous function is the set of variables:</p>\n<pre><code>{\n  global: 2,\n  w: &quot;unused&quot;,\n  y: [whatever has been passed to that wrapper function as its parameter `y`]\n}\n</code></pre>\n<p>Now, the <em>closure</em> is that part of this environment which <em>closes</em> the inner function by supplying the definitions for all its <em>free variables</em>. In our case, the only free variable in the inner function was <code>y</code>, so the closure of that function is this subset of its environment:</p>\n<pre><code>{\n  y: [whatever has been passed to that wrapper function as its parameter `y`]\n}\n</code></pre>\n<p>The other two symbols defined in the environment are <em>not</em> part of the <em>closure</em> of that function, because it doesn\'t require them to run. They are not needed to <em>close</em> it.</p>\n<p>More on the theory behind that here:\n<a href="https://stackoverflow.com/a/36878651/434562">https://stackoverflow.com/a/36878651/434562</a></p>\n<p>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 <code>y</code> to be there when it is called! In other words, it requires the variables from its closure to somehow <em>outlive</em> the wrapper function and be there when needed. Therefore, the inner function has to make a <em>snapshot</em> of these variables which make its closure and store them somewhere safe for later use. (Somewhere outside the call stack.)</p>\n<p>And this is why people often confuse the term <em>closure</em> 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 <em>not</em> the closure itself – they\'re just ways to <em>implement</em> 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 than it actually is.</p>\n'}, {'answer_id': 44915262, 'author': 'totymedli', 'author_id': 1494454, 'author_profile': 'https://Stackoverflow.com/users/1494454', 'pm_score': 3, 'selected': False, 'text': '<h2>tl;dr</h2>\n<p>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.</p>\n<h2>In depth Wikipedia style explanation</h2>\n<p><a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" rel="noreferrer">According to Wikipedia, a closure</a> is:</p>\n<blockquote>\n<p>Techniques for implementing lexically scoped name binding in languages with first-class functions.</p>\n</blockquote>\n<p>What does that mean? Lets look into some definitions.</p>\n<p>I will explain closures and other related definitions by using this example:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function startAt(x) {\n    return function (y) {\n        return x + y;\n    }\n}\n\nvar closure1 = startAt(1);\nvar closure2 = startAt(5);\n\nconsole.log(closure1(3)); // 4 (x == 1, y == 3)\nconsole.log(closure2(3)); // 8 (x == 5, y == 3)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>First-class functions</h3>\n<p>Basically that means <strong>we can use functions just like any other entity</strong>. We can modify them, pass them as arguments, return them from functions or assign them for variables. Technically speaking, they are <a href="https://en.wikipedia.org/wiki/First-class_citizen" rel="noreferrer">first-class citizens</a>, hence the name: first-class functions.</p>\n<p>In the example above, <code>startAt</code> returns an (<a href="https://en.wikipedia.org/wiki/Anonymous_function" rel="noreferrer">anonymous</a>) function which function get assigned to <code>closure1</code> and <code>closure2</code>. So as you see JavaScript treats functions just like any other entities (first-class citizens).</p>\n<h3>Name binding</h3>\n<p><a href="https://en.wikipedia.org/wiki/Name_binding" rel="noreferrer">Name binding</a> is about finding out <strong>what data a variable</strong> (identifier) <strong>references</strong>. The scope is really important here, as that is the thing that will determine how a binding is resolved.</p>\n<p>In the example above:</p>\n<ul>\n<li>In the inner anonymous function\'s scope, <code>y</code> is bound to <code>3</code>.</li>\n<li>In <code>startAt</code>\'s scope, <code>x</code> is bound to <code>1</code> or <code>5</code> (depending on the closure).</li>\n</ul>\n<p>Inside the anonymous function\'s scope, <code>x</code> is not bound to any value, so it needs to be resolved in an upper (<code>startAt</code>\'s) scope.</p>\n<h3>Lexical scoping</h3>\n<p>As <a href="https://en.wikipedia.org/wiki/Scope_(computer_science)" rel="noreferrer">Wikipedia says</a>, the scope:</p>\n<blockquote>\n<p>Is the region of a computer program where the binding is valid: <strong>where the name can be used to refer to the entity</strong>.</p>\n</blockquote>\n<p>There are two techniques:</p>\n<ul>\n<li>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.</li>\n<li>Dynamic scoping: Calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.</li>\n</ul>\n<p>For more explanation, <a href="https://stackoverflow.com/q/1047454/1494454">check out this question</a> and <a href="https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scope_vs._dynamic_scope" rel="noreferrer">take a look at Wikipedia</a>.</p>\n<p>In the example above, we can see that JavaScript is lexically scoped, because when <code>x</code> is resolved, the binding is searched in the upper (<code>startAt</code>\'s) scope, based on the source code (the anonymous function that looks for x is defined inside <code>startAt</code>) and not based on the call stack, the way (the scope where) the function was called.</p>\n<h3>Wrapping (closuring) up</h3>\n<p>In our example, when we call <code>startAt</code>, it will return a (first-class) function that will be assigned to <code>closure1</code> and <code>closure2</code> thus a closure is created, because the passed variables <code>1</code> and <code>5</code> will be saved within <code>startAt</code>\'s scope, that will be enclosed with the returned anonymous function. When we call this anonymous function via <code>closure1</code> and <code>closure2</code> with the same argument (<code>3</code>), the value of <code>y</code> will be found immediately (as that is the parameter of that function), but <code>x</code> 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 <code>x</code> is found to be bound to either <code>1</code> or <code>5</code>. Now we know everything for the summation so the result can be returned, then printed.</p>\n<p>Now you should understand closures and how they behave, which is a fundamental part of JavaScript.</p>\n<h3>Currying</h3>\n<p>Oh, and you also learned what <a href="https://en.wikipedia.org/wiki/Currying" rel="noreferrer">currying</a> is about: you use functions (closures) to pass each argument of an operation instead of using one functions with multiple parameters.</p>\n'}, {'answer_id': 45479869, 'author': 'shohan', 'author_id': 849525, 'author_profile': 'https://Stackoverflow.com/users/849525', 'pm_score': 0, 'selected': False, 'text': '<p>Closures\nWhenever we have a function defined inside another function, the inner function has access to the variables declared\nin the outer function. Closures are best explained with examples.\nIn Listing 2-18, you can see that the inner function has access to a variable (variableInOuterFunction) from the\nouter scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term\nclosure. The concept in itself is simple enough and fairly intuitive.</p>\n\n<pre><code>Listing 2-18:\n    function outerFunction(arg) {\n     var variableInOuterFunction = arg;\n\n     function bar() {\n             console.log(variableInOuterFunction); // Access a variable from the outer scope\n     }\n     // Call the local function to demonstrate that it has access to arg\n     bar(); \n    }\n    outerFunction(\'hello closure!\'); // logs hello closure!\n</code></pre>\n\n<p>source: <a href="http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf" rel="nofollow noreferrer">http://index-of.es/Varios/Basarat%20Ali%20Syed%20(auth.)-Beginning%20Node.js-Apress%20(2014).pdf</a></p>\n'}, {'answer_id': 53794681, 'author': 'arun', 'author_id': 2638170, 'author_profile': 'https://Stackoverflow.com/users/2638170', 'pm_score': 0, 'selected': False, 'text': "<p>Please have a look below code to understand closure in more deep:</p>\n\n<pre><code>        for(var i=0; i&lt; 5; i++){            \n            setTimeout(function(){\n                console.log(i);\n            }, 1000);                        \n        }\n</code></pre>\n\n<p>Here what will be output? <code>0,1,2,3,4</code> not that will be <code>5,5,5,5,5</code> because of closure</p>\n\n<p>So how it will solve? Answer is below:</p>\n\n<pre><code>       for(var i=0; i&lt; 5; i++){\n           (function(j){     //using IIFE           \n                setTimeout(function(){\n                               console.log(j);\n                           },1000);\n            })(i);          \n        }\n</code></pre>\n\n<p>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 <code>setTimeout</code> function five time and print <code>5,5,5,5,5</code></p>\n\n<p>Here how it solve using IIFE i.e Immediate Invoking Function Expression</p>\n\n<pre><code>       (function(j){  //i is passed here           \n            setTimeout(function(){\n                           console.log(j);\n                       },1000);\n        })(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\n</code></pre>\n\n<p>For more, please understand execution context to understand closure.</p>\n\n<ul>\n<li><p>There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked</p>\n\n<pre><code> for(let i=0; i&lt; 5; i++){           \n     setTimeout(function(){\n                    console.log(i);\n                },1000);                        \n }\n\nOutput: 0,1,2,3,4\n</code></pre></li>\n</ul>\n\n<p>=> More explanation:</p>\n\n<p>In memory, when for loop execute picture make like below:</p>\n\n<p>Loop 1)</p>\n\n<pre><code>     setTimeout(function(){\n                    console.log(i);\n                },1000);  \n</code></pre>\n\n<p>Loop 2)</p>\n\n<pre><code>     setTimeout(function(){\n                    console.log(i);\n                },1000); \n</code></pre>\n\n<p>Loop 3)</p>\n\n<pre><code>     setTimeout(function(){\n                    console.log(i);\n                },1000); \n</code></pre>\n\n<p>Loop 4)</p>\n\n<pre><code>     setTimeout(function(){\n                    console.log(i);\n                },1000); \n</code></pre>\n\n<p>Loop 5)</p>\n\n<pre><code>     setTimeout(function(){\n                    console.log(i);\n                },1000);  \n</code></pre>\n\n<p>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 <code>setTimeout</code> out five time it prints <code>5,5,5,5,5</code></p>\n\n<p>so to resolve this use IIFE as explain above.</p>\n"}, {'answer_id': 55753213, 'author': 'rahul sharma', 'author_id': 11049404, 'author_profile': 'https://Stackoverflow.com/users/11049404', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Closure</strong> is a feature in JavaScript where a function has access to its own scope variables, access to the outer function variables and access to the global variables.</p>\n\n<p>Closure has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.</p>\n\n<p>The inner function can access the variables defined in its own scope, the outer function’s scope, and the global scope. And the outer function can access the variable defined in its own scope and the global scope.</p>\n\n<p><strong>Example of Closure</strong>:</p>\n\n<pre class="lang-js prettyprint-override"><code>var globalValue = 5;\n\nfunction functOuter() {\n  var outerFunctionValue = 10;\n\n  //Inner function has access to the outer function value\n  //and the global variables\n  function functInner() {\n    var innerFunctionValue = 5;\n    alert(globalValue + outerFunctionValue + innerFunctionValue);\n  }\n  functInner();\n}\nfunctOuter();  \n</code></pre>\n\n<p>Output will be 20 which sum of its inner function own variable, outer function variable and global variable value.</p>\n'}, {'answer_id': 55979154, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Currying : It allows you to partially evaluate a function by only passing in a subset of its arguments. Consider this:</p>\n\n<pre><code>function multiply (x, y) {\n  return x * y;\n}\n\nconst double = multiply.bind(null, 2);\n\nconst eight = double(4);\n\neight == 8;\n</code></pre>\n\n<p>Closure: A closure is nothing more than accessing a variable outside of a function's scope. It is important to remember that a function inside a function or a nested function isn't a closure. Closures are always used when need to access the variables outside the function scope.</p>\n\n<pre><code>function apple(x){\n   function google(y,z) {\n    console.log(x*y);\n   }\n   google(7,2);\n}\n\napple(3);\n\n// the answer here will be 21\n</code></pre>\n"}, {'answer_id': 56366052, 'author': 'Rumel', 'author_id': 4360546, 'author_profile': 'https://Stackoverflow.com/users/4360546', 'pm_score': 0, 'selected': False, 'text': '<p>Closure is very easy. We can consider it as follows :\nClosure = function + its lexical environment</p>\n\n<p>Consider the following function:</p>\n\n<pre><code>function init() {\n    var name = “Mozilla”;\n}\n</code></pre>\n\n<p>What will be the closure in the above case ? \nFunction init() and variables in its lexical environment ie name.\n<strong>Closure</strong> = init() + name</p>\n\n<p>Consider another function :</p>\n\n<pre><code>function init() {\n    var name = “Mozilla”;\n    function displayName(){\n        alert(name);\n}\ndisplayName();\n}\n</code></pre>\n\n<p>What will be the closures here ?\nInner function can access variables of outer function. displayName() can access the variable name declared in the parent function, init(). However, the same local variables in displayName() will be used if they exists.</p>\n\n<p><strong>Closure 1 :</strong> init function +  ( name variable + displayName() function) --> lexical scope</p>\n\n<p><strong>Closure 2 :</strong> displayName function +  ( name variable ) --> lexical scope</p>\n'}, {'answer_id': 58013619, 'author': 'Claudio', 'author_id': 7056679, 'author_profile': 'https://Stackoverflow.com/users/7056679', 'pm_score': 2, 'selected': False, 'text': '<h1>Closures provide JavaScript with state.</h1>\n\n<p>State in programming simply means remembering things.</p>\n\n<p>Example</p>\n\n<pre><code>var a = 0;\n\na = a + 1; // =&gt; 1\na = a + 1; // =&gt; 2\na = a + 1; // =&gt; 3\n</code></pre>\n\n<p>In the case above, state is stored in the variable "a". We follow by adding 1 to "a" several times. We can only do that because we are able to "remember" the value. The state holder, "a", holds that value in memory.</p>\n\n<p>Often, in programming languages, you want to keep track of things, remember information and access it at a later time.</p>\n\n<p>This, <strong>in other languages</strong>, is commonly accomplished through the use of classes. A class, just like variables, keeps track of its state. And instances of that class, in turns, also have state within them. State simply means information that you can store and retrieve later.</p>\n\n<p>Example</p>\n\n<pre><code>class Bread {\n  constructor (weight) {\n    this.weight = weight;\n  }\n\n  render () {\n    return `My weight is ${this.weight}!`;\n  }\n}\n</code></pre>\n\n<p>How can we access "weight" from within the "render" method? Well, thanks to state. Each instance of the class Bread can render its own weight by reading it from the "state", a place in memory where we could store that information.</p>\n\n<p>Now, <strong>JavaScript is a very unique language</strong> which historically does not have classes (it now does, but under the hood there\'s only functions and variables) so Closures provide a way for JavaScript to remember things and access them later.</p>\n\n<p>Example</p>\n\n<pre><code>var n = 0;\nvar count = function () {\n  n = n + 1;\n  return n;\n};\n\ncount(); // # 1\ncount(); // # 2\ncount(); // # 3\n</code></pre>\n\n<p>The example above achieved the goal of "keeping state" with a variable. This is great! However, this has the disadvantage that the variable (the "state" holder) is now exposed. We can do better. We can use Closures.</p>\n\n<p>Example</p>\n\n<pre><code>var countGenerator = function () {\n  var n = 0;\n  var count = function () {\n    n = n + 1;\n    return n;\n  };\n\n  return count;\n};\n\nvar count = countGenerator();\ncount(); // # 1\ncount(); // # 2\ncount(); // # 3\n</code></pre>\n\n<h2>This is fantastic.</h2>\n\n<p>Now our "count" function can count. It is only able to do so because it can "hold" state. The state in this case is the variable "n". This variable is now closed. Closed in time and space. In time because you won\'t ever be able to recover it, change it, assign it a value or interact directly with it. In space because it\'s geographically nested within the "countGenerator" function.</p>\n\n<p>Why is this fantastic? Because without involving any other sophisticated and complicated tool (e.g. classes, methods, instances, etc) we are able to\n1. conceal\n2. control from a distance</p>\n\n<p>We conceal the state, the variable "n", which makes it a private variable!\nWe also have created an API that can control this variable in a pre-defined way. In particular, we can call the API like so "count()" and that adds 1 to "n" from a "distance". In no way, shape or form anyone will ever be able to access "n" except through the API.</p>\n\n<h2>JavaScript is truly amazing in its simplicity.</h2>\n\n<p>Closures are a big part of why this is.</p>\n'}, {'answer_id': 58125389, 'author': 'GraceMeng', 'author_id': 9687097, 'author_profile': 'https://Stackoverflow.com/users/9687097', 'pm_score': 0, 'selected': False, 'text': '<p>A simple example in Groovy for your reference:</p>\n\n<pre><code>def outer() {\n    def x = 1\n    return { -&gt; println(x)} // inner\n}\ndef innerObj = outer()\ninnerObj() // prints 1\n</code></pre>\n'}, {'answer_id': 66317675, 'author': 'Kim Mens', 'author_id': 13339955, 'author_profile': 'https://Stackoverflow.com/users/13339955', 'pm_score': 0, 'selected': False, 'text': '<p>Here is an example illustrating a closure in the Scheme programming language.</p>\n<p>First we define a function defining a local variable, not visible outside the function.</p>\n<pre><code>; Function using a local variable\n(define (function)\n  (define a 1)\n  (display a) ; prints 1, when calling (function)\n  )\n(function) ; prints 1\n(display a) ; fails: a undefined\n</code></pre>\n<p>Here is the same example, but now the function uses a global variable, defined outside the function.</p>\n<pre><code>; Function using a global variable\n(define b 2)\n(define (function)\n  (display b) ; prints 2, when calling (function)\n  )\n(function) ; prints 2\n(display 2) ; prints 2\n</code></pre>\n<p>And finally, here is an example of a function carrying its own closure:</p>\n<pre><code>; Function with closure\n(define (outer)\n  (define c 3)\n  (define (inner)\n    (display c))\n  inner ; outer function returns the inner function as result\n  )\n(define function (outer))\n(function) ; prints 3\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/36636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3786/']