Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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

share|improve this question
    
single is the correct answer. –  Ingo Jan 21 '12 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. –  PersonalNexus Jan 21 '12 at 11:14
add comment

2 Answers

up vote 12 down vote accepted

"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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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