Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A closure is basically a function B nested inside a function A that can access A's local variables:</p> <pre><code>function A() { var x = 5; function B() { print(x); } return B; } </code></pre> <p>If you come from a C++ background, this is rather hard to digest. When we try to call the function returned by A, what <code>x</code> will it refer to? Won't that <code>x</code> be invalid since <code>A()</code> terminated?</p> <p>The answer is that <code>x</code> actually lives on. That <code>B</code> we returned actually carries <code>x</code> around with it implicitly. Cool, eh?</p> <p>In a more general sense, a closure is a function bound to some data. In a language without closures like C, every program has a fixed number of functions. With closures, you can, in a sense, "create functions" by binding them to dynamic data. Of course, nobody's stopping you from emulating closures in C, but it can be a pain sometimes.</p> <p>Closures are really useful. For instance, suppose we want to implement our own "for loop":</p> <pre><code>function loop(count, f) { for (var i = 0; i &lt; count; i++) f(i); } var array = [0,1,2,3,4]; loop(5, function(i) { print(array[i]); }); </code></pre> <p>Being allowed to access outside variables without doing a bunch of extra nonsense keeps code nice and simple. Without closures, you might have to pass a context variable to the <code>loop</code> function instead:</p> <pre><code>function loop(count, f, ctx) { for (var i = 0; i &lt; count; i++) f(i, ctx); } var array = [0,1,2,3,4]; loop(5, function(i, ctx) { print(ctx[i]); }, array); </code></pre> <p>Another example: suppose we want to register a callback in jQuery, but it may be executed long after the function and its caller and its caller's caller are done running:</p> <pre><code>$(document).ready(function(){ var clicked = 0; $('#button').click(function(){ clicked++; alert("You've pressed the button " + clicked + " times."); }); }); </code></pre> <p>If JavaScript were more like C++ (before C++0x), that <code>clicked</code> variable would be long gone by the time the function given to <code>$(document).ready()</code> was called, and the button clicking callback would have undefined behavior.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload