This is an attempt to clear up several (possible) misunderstandings about closures that appear in some of the other answers.
- A closure is not only created when you return an inner function. InIn fact, the enclosing function does not need to return at all in order for its closure to be created. YouYou might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be called immediately or any time later. ThereforeTherefore, the closure of the enclosing function is probably created as soon as the enclosing function is called since any inner function has access to that closure whenever the inner function is called, before or after the enclosing function returns.
- A closure does not reference a copy of the old values of variables in its scope. TheThe variables themselves are part of the closure, and so the value seen when accessing one of those variables is the latest value at the time it is accessed. ThisThis is why inner functions created inside of loops can be tricky, since each one has access to the same outer variables rather than grabbing a copy of the variables at the time the function is created or called.
- The "variables" in a closure include any named functions declared within the function. TheyThey also include arguments of the function. AA closure also has access to its containing closure's variables, all the way up to the global scope.
- Closures use memory, but they don't cause memory leaks since JavaScript by itself cleans up its own circular structures that are not referenced. IEInternet Explorer memory leaks involving closures are created when it fails to disconnect DOM attribute values that reference closures, thus maintaining references to possibly circular structures.