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
4
votes
3 answers

Functional Programming: Are maps sequential? Implications for closures

I will illustrate with Julia: Suppose I have a function counter() that is a closure. function mycl() …
Lindon
  • 1,292
  • 1
  • 10
  • 21
4
votes
1 answer

Why 'for .. in' allowed in closures?

Mutable values are not allowed in closures, but the for .. in expression is ok. In C# the for loop updates the iterator, but not in F# as it seems. How and why?
aikixd
  • 506
  • 5
  • 16
4
votes
1 answer

Iterate over and call closures in FnMut vector

I have a struct similar to this: struct Foo<'a> { callbacks: Vec<&'a FnMut(u32)>, } I want to call each callback, but my attempt doesn't work: fn foo(&mut self) { for f in &mut self.callbacks { (*f)(0); } } I get this…
someguy
  • 7,144
  • 12
  • 43
  • 57
4
votes
4 answers

How to map on a vec and use a closure with pattern matching in Rust

I'd like to use map to iterate over an array and do stuff per item and get rid of the for loop. An error which I do not understand blocks my attempt. What I want to achieve is to iterate through a vector of i32 and match on them to concat a string…
xetra11
  • 7,671
  • 14
  • 84
  • 159
4
votes
3 answers

How to create new closure cell objects?

I need to monkey-patch my library to replace an instance of a symbol, and it's getting referenced by some function closures. I need to copy those functions (since I also need access to original unpatched version of the function as well), but…
Yaroslav Bulatov
  • 57,332
  • 22
  • 139
  • 197
4
votes
1 answer

Swift generic closure

I'm building a library for static table views and it works fine, but I encountered a problem with generic closures. It looks like this so far: orderForm = Form(tableView: orderTable) { f in f.section { s in s.footer("Při platbě nejsou…
4
votes
2 answers

Can swift exit out of the root closure?

In Swift, if I'm inside of a closure, that is itself inside of another function, is there a way to exit out of the function itself? Here's an example of what this might look like using closures from the GCDKit library. func test() { …
Evan Conrad
  • 3,993
  • 4
  • 28
  • 46
4
votes
3 answers

Stateful function pipeline

The code explains itself. val s = Seq(1,1,1) val res: Seq[Int] = s.map(...) .check(count how many 1s, if > 2 throw Exception) .map(...) I am searching the simple solution to this check function . I can…
4
votes
1 answer

Typescript lambdas and closure (scope)

I load some data for multiple users and I want to store it into a javascript array. In pure typescript, I will write it like that: for(var i = 0; i < 5; i++) { promise[i] = httpquery.then( (data) => { this.usersData[i] = data } …
Adavo
  • 865
  • 3
  • 11
  • 21
4
votes
2 answers

NodeJS callback - Access to 'res'

I am using the Express framework and I have the following in one of my route files: var allUsersFromDynamoDb = function (req, res) { var dynamodbDoc = new AWS.DynamoDB.DocumentClient(); var params = { TableName: "users", …
vksinghh
  • 223
  • 4
  • 16
4
votes
2 answers

Retain cycle happens when passing method instead of closure

In Swift we can nice feature we didn't have in ObjC: it's possible to use a method everywhere you would use a closure. But it can lead to retain cycles. Look at this example: import Foundation class C1 { let closure: Void -> Void …
Alexander Doloz
  • 4,078
  • 1
  • 20
  • 36
4
votes
2 answers

Differrence between closure and function as argument in swift

I have almost 4 years of experience with Objective C and a newbie in swift. Am trying to understand the concept of swift from the perspective of Objective C. So if I am wrong please guide me through :) In objective c, we have blocks (chunck of code…
Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78
4
votes
2 answers

Returning closures which capture outer variables in Rust

As the title states I am looking to return a closure from a function which has some initial, mutable state. In the following examples CowRow is a struct with a time field. It also has a String field, so is thus not copyable. Concretely, I would like…
josh
  • 1,544
  • 2
  • 16
  • 27
4
votes
1 answer

What's the difference between closures and callbacks in Swift?

I was asked whether Objective C blocks are more similar to closures or callbacks. However, the definition of a callback seems nearly identical to a closure, at least in this example borrowed from…
squarehippo10
  • 1,855
  • 1
  • 15
  • 45
4
votes
3 answers

using _gaq asynch in closures

When using var _gaq = _gaq || []; within a script tag what would be needed to support this in a closure to add analytics async requests. i.e. experiment = (function(){ var _gaq = _gaq || []; _gaq.push(['_setAccount',…
claya
  • 1,920
  • 1
  • 18
  • 32