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
1 answer

Why does the closure for `take_while` take its argument by reference?

Here is an example from Rust by Example: fn is_odd(n: u32) -> bool { n % 2 == 1 } fn main() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Functional approach let…
qed
  • 22,298
  • 21
  • 125
  • 196
4
votes
2 answers

How do I declare, create, and use method pointers in Swift?

I'm not talking about pointers to C functions, but to a method within a Swift type. struct Test: GeneratorType { var methodPointer: mutating () -> Bool? // Non-working guess var which: Bool init() { which = false …
CTMacUser
  • 1,996
  • 1
  • 16
  • 27
4
votes
2 answers

Shorter ways to specify completion handler

I've had this problem a couple of times now, so thought I'd reach out. I have a number of network interfaces responsible for making Async network calls, there's about 5/6 functions in each interface which all use a completion handler with the same…
Ollie
  • 1,926
  • 1
  • 20
  • 35
4
votes
1 answer

Using QuerySort

I am trying to use ColdFusion 2016 Query sort I am basing the sort on Array sort by Raymond Camden http://www.raymondcamden.com/2012/08/14/Another-ColdFusion-10-Closures-Post/ qryTest = QueryNew("ID,Name"); qryTest.AddRow([ …
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
4
votes
1 answer

Chrome devtools console does not display closure

I was trying out a very basic example of Javascript closure, but I am not able to visualize it in Chrome devtools. Please see the screenshot. I have created a global variable var p = 3; and a function function f1() { var q = 2; return…
Roy
  • 503
  • 2
  • 8
  • 20
4
votes
1 answer

Closure Capture Context Swift

I get this error when I try to change variables in the closure: A C function pointer cannot be formed from a closure that captures context Is there a work around or is it possible to still change the variables within the closure? My Code: let…
HovyTech
  • 299
  • 5
  • 19
4
votes
3 answers

Binding click event handlers in a loop causing problems in jQuery

I am trying to run the following code: I pass parameter to a function, but it always has the value of the last object run through the loop. I read some articles about it on stackoverflow, but I couldn't find out how to make it run in my solution.…
Kel
  • 309
  • 1
  • 8
  • 25
4
votes
1 answer

C++ type of lambda closure returned from functions

Consider the following example code: int main() { auto id = []() { auto ret = [](auto u) { return u; }; return ret; }; //same closure type -- prints '1' auto f1 = id(); auto g1 = id(); …
davidhigh
  • 14,652
  • 2
  • 44
  • 75
4
votes
2 answers

Closure default initializer missing - swift closure variable declaration?

I declared closure outside viewController class, I created one variable of that closure inside viewController class, but it shows the error of default initializer missing for this closure. I understand the consequences about variable and constant…
Kiran Jasvanee
  • 6,362
  • 1
  • 36
  • 52
4
votes
2 answers

CoreAudio AudioObjectRemovePropertyListener not working in Swift

I am working with CoreAudio in swift and needed to find when the user changes the system volume. I can get the volume correctly and even add a property listener to find when the user changes the volume. But I need to stop listening at some point (if…
BoteRock
  • 467
  • 6
  • 12
4
votes
1 answer

r - Error in tag$head: object of type 'closure' is not subsettable

I got this error when I Run my Shiny app on my laptop. App worked before I added a line of code with library(git2r). Below my code. Can anyone assist? Thanks. ui.R league_desc <- c("Premier League","Serie A","Bundesliga","La Liga") shinyUI( …
NB75
  • 51
  • 3
4
votes
1 answer

Swift variable declaration with closure

I saw a declaration which confuses me. ( the grammar here) static var dateFormatter: NSDateFormatter = { var formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() To declare a variable, it looks like it…
Yao
  • 709
  • 2
  • 11
  • 22
4
votes
2 answers

How to create function with two closures as params in Swift?

I need to translate such a func from Objective-C to Swift language. But can't find an example and can't get how to send 2 closures into func in Swift. For example, original function in Objective-C: - (void)getForDemoDataWithToken:(Token…
Bogdan Laukhin
  • 1,454
  • 2
  • 17
  • 26
4
votes
2 answers

How do you expose a global javascript function without ESLint no-unused-var error?

The following code is valid in ESLint with Google's style guide with one exception; the closure function Counter gets a no-unused-vars error when the script is checked using ESLint. /** * Create a counter that is incremented and returned when…
tayden
  • 570
  • 7
  • 20
4
votes
0 answers

Convoluted tree structure causes the GC to pause indefinitely

I am doing some machine learning self study and currently I am implementing reverse mode automatic differentiation as practice. The way the program works is by essentially overloading common expressions like multiplication, addition and so on and…
Marko Grdinić
  • 3,798
  • 3
  • 18
  • 21