Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;

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

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

Your Answer


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.