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)?

  • `single` is the correct answer. – Ingo Jan 21 '12 at 10:54
  • 2
    From the [Closure article on Wikipedia](http://en.wikipedia.org/wiki/Closure_%28computer_science%29) (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`. – PersonalNexus Jan 21 '12 at 11:14

2 Answers2

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.

Mason Wheeler
  • 82,151
  • 24
  • 234
  • 309
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.

dietbuddha
  • 8,677
  • 24
  • 36