7

Let's take the following (JavaScript) code that returns a function that closes over variables x and y to illustrate:

function test() {
  var x = Math.random();
  var y = Math.random();
  var f = function() { 
    console.log(x, y); 
  };

  return f;
}
test()();

The code is nonsensical, I just want to close over x and y.

Variables x and y don't exist outside of the function test but they remain available in the function f.

Barring any compiler optimizations (like inlining), do we say there is a single closure (created by f), or do we say there are two closures (for/over x and y)?

2
  • single is the correct answer.
    – Ingo
    Jan 21, 2012 at 10:54
  • 2
    From the Closure article on Wikipedia (emphasis mine): "a closure [...] is a function together with a referencing environment for the non-local variables of that function". To answer your question: it's a single closure created by f. Jan 21, 2012 at 11:14

2 Answers 2

12

"A closure" is a function that closes over one or more variables, not the variable(s) that are closed over. So it's a single closure.

3

A closure is a first class function that captures the lexical bindings of variables defined in it's environment. When it captures the bindings it is said to have "closed over" the variables.

Note: this means closures only exist at runtime (once it has "closed over" variables).

So in the example above a single closure is created when the code is executed. This closure is "closed over" the variables x and y.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.