Questions tagged [closures]

A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.

A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.

JavaScript closure

A basic example of closure in JavaScript can be shown with a counter:

function increment () {
    var count = 0;
    return function () { // returning function
         count++; // increment the count
         return count;
    };
}

var foo = increment(); // foo is now a closure function, where count = 0
foo(); // calls the closure which yields 1

The reason why increment is considered to be a closure is because it's a local variable. In this case, count is persisting when assigned to the variable foo. This persistence occurs because the context of foo is taken from increment when it's declared.

The key point with a closure is that the environment of the function is 'closed' to a hosting object.

var bar = increment(); // bar is now another closure function, with count initialized to 0
bar(); // calls the closure which yields 1, not 2.

jQuery closures

A more practical example of a closure is the jQuery library. jQuery itself is one big closure. It's declared like this:

var jQuery = (function() { // Here is the closure
    // Define a local copy of jQuery
    var jQuery = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'.
        return new jQuery.fn.init( selector, context, rootjQuery );
    },
    ...
}) ( window );

Let's take a deeper look at this. jQuery's closure is actually an immediately invoked function expression or a closure that is immediately called. Let's take our original increment example and represent it in the form that jQuery uses:

var foo = (function () {
    var count = 0;
    return function () {
        count++; // Increment the count
        return count;
    };
}) ();

foo(); // Yields 1

At first glance, this looks quite a bit different from our original example, but take another look. The only difference is that this example is wrapped in parentheses. (function () {...}) ();. These parentheses are returning the result of what's inside of them.

The first parentheses are returning a function that has count = 0. This is the same as calling increment() in our first example and the second set of parentheses is calling the returned function.

Resources

For a history of closures as a programming language construct see the Wikipedia Closure page.

In Ruby, closures are called blocks.

8908 questions
7621
votes
86 answers

How do JavaScript closures work?

How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves? I have seen the Scheme example given on Wikipedia,…
Bite code
  • 578,959
  • 113
  • 301
  • 329
3221
votes
45 answers

JavaScript closure inside loops – simple practical example

var funcs = []; // let's create 3 functions for (var i = 0; i < 3; i++) { // and store them in funcs funcs[i] = function() { // each should log its value. console.log("My value:", i); }; } for (var j = 0; j < 3; j++) { // and now…
nickf
  • 537,072
  • 198
  • 649
  • 721
981
votes
26 answers

How are lambdas useful?

I'm trying to figure out Python lambdas. Is lambda one of those "interesting" language items that in real life should be forgotten? I'm sure there are some edge cases where it might be needed, but given the obscurity of it, the potential of it being…
meade
  • 22,875
  • 12
  • 32
  • 36
975
votes
16 answers

What is the difference between a 'closure' and a 'lambda'?

Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused. And now that we're here, how do they differ from a regular function?
sker
  • 17,842
  • 8
  • 37
  • 41
813
votes
43 answers

Static variables in JavaScript

How can I create static variables in Javascript?
Rajat
  • 32,970
  • 17
  • 67
  • 87
579
votes
12 answers

JavaScript closures vs. anonymous functions

A friend of mine and I are currently discussing what is a closure in JS and what isn't. We just want to make sure we really understand it correctly. Let's take this example. We have a counting loop and want to print the counter variable on the…
leemes
  • 44,967
  • 21
  • 135
  • 183
515
votes
21 answers

What is the purpose of a self executing function in javascript?

In javascript, when would you want to use this: (function(){ //Bunch of code... })(); over this: //Bunch of code...
Ej.
  • 5,429
  • 3
  • 18
  • 15
480
votes
6 answers

In PHP, what is a closure and why does it use the "use" identifier?

I'm checking out some PHP 5.3.0 features and ran across some code on the site that looks quite funny: public function getTotal($tax) { $total = 0.00; $callback = /* This line here: */ function ($quantity, $product) use…
SeanDowney
  • 17,368
  • 20
  • 81
  • 90
464
votes
10 answers

What does "nonlocal" do in Python 3?

What does nonlocal do in Python 3.x? To close debugging questions where OP needs nonlocal and doesn't realize it, please use Is it possible to modify variable in python that is in outer, but not global, scope? instead. Although Python 2 is…
ooboo
  • 16,259
  • 13
  • 37
  • 32
381
votes
10 answers

What underlies this JavaScript idiom: var self = this?

I saw the following in the source for WebKit HTML 5 SQL Storage Notes Demo: function Note() { var self = this; var note = document.createElement('div'); note.className = 'note'; note.addEventListener('mousedown', function(e) { return…
Thomas L Holaday
  • 13,614
  • 6
  • 40
  • 51
367
votes
8 answers

What do lambda function closures capture?

Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code: adders=[None, None, None, None] for i in [0,1,2,3]: adders[i]=lambda a: i+a print adders[1](3) It builds…
Boaz
  • 25,331
  • 21
  • 69
  • 77
347
votes
24 answers

What is a practical use for a closure in JavaScript?

I'm trying my hardest to wrap my head around JavaScript closures. I get that by returning an inner function, it will have access to any variable defined in its immediate parent. Where would this be useful to me? Perhaps I haven't quite got my head…
alex
  • 479,566
  • 201
  • 878
  • 984
323
votes
3 answers

Access to Modified Closure

string [] files = new string[2]; files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml"; files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml"; //Resharper complains this is an "access to modified closure" for (int i =…
Vyas Bharghava
  • 6,372
  • 9
  • 39
  • 59
307
votes
21 answers

What's the nearest substitute for a function pointer in Java?

I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer…
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
280
votes
10 answers

Captured variable in a loop in C#

I met an interesting issue about C#. I have code like below. List> actions = new List>(); int variable = 0; while (variable < 5) { actions.Add(() => variable * 2); ++ variable; } foreach (var act in actions) { …
Morgan Cheng
  • 73,950
  • 66
  • 171
  • 230
1
2 3
99 100