4

I have read 10s of SO references on closures, MDN references and other blog articles. They all seem to define closures in their own ways. For example, From MDN documentation:

function makeFunc() {
  var name = "Mozilla";
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

And here goes their explanation of closure:

Normally, the local variables within a function only exist for the duration of that function's execution. Once makeFunc() has finished executing, it is reasonable to expect that the name variable will no longer be accessible. Since the code still works as expected, this is obviously not the case.

The solution to this puzzle is that myFunc has become a closure. A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created. In this case, myFunc is a closure that incorporates both the displayName function and the "Mozilla" string that existed when the closure was created.

This below StackOverflow post answers closures as a stack of visible scopes. What types of scope exist in Javascript?

Where I am confused: is closure an object? Or is it just a "anomalous scoping situation" where inner nested function has access to a variable defined outside of itself but local to the container parent function, even after parent function has already executed? Is closure an object referring to this nested function (scope) situation like myFunc or is it the inner function itself?

Community
  • 1
  • 1
Athapali
  • 1,091
  • 4
  • 25
  • 48
  • I am inclined to close this question as a duplicate. However, you seem to have done some research. Perhaps this question and answer might help clear the doubts you have: http://stackoverflow.com/q/12930272/783743 – Aadit M Shah Jan 29 '15 at 17:01
  • @AaditMShah Thank you so much! I have read your answers on closures and scoping and they are amazing!! Thank you for taking time to answer these questions for confused folks like me!! – Athapali Jan 29 '15 at 17:06
  • You've also read [How do JavaScript closures work?](http://stackoverflow.com/q/111102/1048572) – Bergi Jan 29 '15 at 18:01
  • One definition? "*A [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)) is a function [object] with a reference to a scope in which its free variables are looked up*". In the strict sense, we use the term only for functions where those free variables are not global. – Bergi Jan 29 '15 at 18:09

3 Answers3

2

To put it in a succinct way,

The function inside another function, has the access to the variables declared in the outer function. In case the function is in the global context, it obviously has the access to the global variables.

More context:

var v1; // I'm accessible anywhere    
function a() {
    var v2;
    function b() { // I can access v2 and v1
        var v3;
        function c() {  // I can access v1, v2, v3
            var v4;
        }
        return c;
    }
    return b();
}
var f = a();

In the above, a, b, c all are closures, which have access to their respective parent scope and this goes on recursively till window or global context.


In general, every function is a closure. But we only come to think of them, when we implement something, that actually depends on closure, such as factory functions.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 1
    How many closures are defined in the example given in this post? http://stackoverflow.com/questions/12543395/what-types-of-scope-exist-in-javascript?rq=1 .Is it one closure or 5 closures? – Athapali Jan 29 '15 at 17:02
  • 3
    @SariksaThapa Technically, every function in JavaScript is a closure because every function in JavaScript carries its lexical context with it. However, closures are only interesting when the values they close over go out of scope (which is what makes closures noticeable). – Aadit M Shah Jan 29 '15 at 17:06
  • ++ but stop editing! you answer is getting less succinct! :-D Excellent final point BTW. – G. Cito Jan 29 '15 at 17:15
1

You can think of JS function as this structure:

class Function : Object {
  bytes      bytecode;
  varframe   varsAndArgs;
}

class varframe{
  array<value>  values;
  ptr<varframe> parent;
}

So each function instance in JS is technically a closure. In toplevel functions that parent pointer is null.

So when you define

function makeFunc() {
  var name = "Mozilla";
  function displayName() {
    alert(name);
  }
  return displayName;
}

that displayName (const/variable) will contain instance of class Function that will contain reference to its own varframe of this structure:

varframe(displayName) 
  values[0] // empty array, no variables in it
  parent -> varframe(makeFunc) 
              values[1] // one variable "name" at index 0;
              parent = null    

Thus closure is a structure holding reference to code and reference to chain of varframes ( a.k.a. callframes ).

c-smile
  • 26,734
  • 7
  • 59
  • 86
0

In the past a lot of course material and references emphasized the OO aspects of JavaScript sometimes to the neglect of functional approaches. I think that began to change with the development of frameworks and extensive collections of JS libraries. Secrets of the JavaScript Ninja makes the case that mastering functions is a fundamental part of effectively using JavaScript. In Ninja the definition of a closure is more general:

"... closures allow a function to access all the variables, as well as other functions, that are in scope when the function itself is declared."

                                         -- "Chapter 5: Closing in on closures"

Discussing closures, Effective JavaScript puts it (more or less) this way:

  • a function can refer to variables defined outside of its scope;
  • functions can refer to variables defined by another function after the second function has returned (because in JavaScript functions are objects);
  • a function can contain internal functions that are "closed over" and which can modify properties of the enclosing function.

The source code for Effective JavaScript Chapter 2. Item 11 "Get Comfortable with Closures" is on gibhub at:

The neat thing about an enclosed function is that it doesn't need a name if you don't plan on calling it explicitly: it can be anonymous and simply be evaluated as part of the outer function.

Community
  • 1
  • 1
G. Cito
  • 6,210
  • 3
  • 29
  • 42
  • 1
    "*can refer to variables returned by another function*" sounds wrong to me. A function cannot return a variable. – Bergi Jan 29 '15 at 18:04
  • changed it ... a function is an object that can have a set of defined properties and a closure can store a references to them ... – G. Cito Jan 29 '15 at 18:09