4

I am doing a course which is going through scope/closures and briefly mentions garbage collection. During the course a question is posed:

How long does the scope stay around? And the answer was—until there's no longer any references to it. Yep, so what we basically said was, a closure is kind of like a reference to a hidden scope object. So as long as there's some function that still has a closure over the scope, that scope's going to stay around. But as soon as that closure goes away, scope can get garbage collected. "

var sum = function sumHndlr(x, y) {
    if (y !== undefined) {
        return x + y;
    } else {
        return function(y) {
            return x + y;
        }
    }
}

So to me, the reference to the closure is when we assigned the function to the sum variable, but won't that mean it lasts forever or am I not understanding the way the js will execute in regards to the compiler parser etc.?

5
  • What do you mean by "forever"? Yes, the closure will last as long as sum, but that's not forever... Commented May 22, 2016 at 17:59
  • Well maybe I need more clarification of what's actually happening with garbage collection. Because currently I am thinking of garbage collection like when you'd remove an event listener. Maybe you can explain why it's not forever. Thanks! Commented May 22, 2016 at 18:04
  • 2
    sum/sumHndlr is no closure. You have to call it (without y) to get one. And then that one will stay around (along with the x it closes over) as long as you keep it somewhere. Show us that call if you want us to tell more. Commented May 22, 2016 at 18:07
  • Right— I thought that was right. The inner function is the function which is remembering it's lexical scope. I guess I am not getting how would that go away? To me I am thinking that would happen if you assigned sum to null or something. But now I am guessing. Commented May 22, 2016 at 18:13
  • 1
    @AntonioOrtiz: The reference from the function to the scope never goes away. The scope can only be garbage collected when all functions pointing to it are as well. If you did var add2 = sum(2);, then assigning add2 = null will make the function eligible for garbage collection. Commented May 22, 2016 at 20:57

1 Answer 1

3

Very briefly, garbage collection is a background process of the Javascript interpreter / virtual machine that automatically frees the memory of objects no longer needed by your program.

For example, since you think of it for event listeners: when you remove an event listener (a function usually) from some event dispatcher, it is likely that no other part of the program will have a reference to the event listener. Therefore, the garbage collector can and will (at some unknown time) free the memory that was taken by the event listener.

Since a closure references a scope object, in order to garbage-collect a closure it needs not only be unreferenced, but also the scope.

If I modify a bit your example:

/* some stuff ... */
function add10(a) {
  var adder = function (x) {
     return function(y) {
       return x + y;
     }
  }

  var sum = adder(10); //creates a closure
  return sum(a);
}

var thirty = add10(20);

/* Some more stuff ... */

After add10 is called, even though the program continues to execute some more stuff, the garbage collector can free the memory associated to the closure sum, because it is no longer referenced, nor is the scope associated to it.

Whereas in this example:

/* some stuff ... */
function add10AndGet20Adder(a) {
  var adders = function (x, y) {
     return [function(z) {
       return x + z;
     }, function(z) {
       return y + z;
     }]
  }

  var sums = adders(10, 20); //creates a closure
  return [sums[0](a), sums[1]];
}

var result = add10AndGet20Adder(50);
var sixty = result[0];
var add20 = result[1];

/* Some more stuff ... */

When executing some more stuff, sums[0] is no longer referenced, BUT add20 (sums[1]) still has a reference to the scope that references x andy, therefore none of the two closures in sums can be freed by the garbage collector, until add20 is referenced by the program.

I hope this makes it clearer, even though the examples are of course nowhere close to real code. In practice, you need to worry about this only if you develop a long-lived program (such as a single page application or nodeJS server) with complicated usage of closures. Otherwise, the memory usage of the closures is unlikely to be a problem.

This SO question gives more details about Javascript garbage collection: What is JavaScript garbage collection?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that detailed explanation using that unique form of a function (the second one) - well maybe unique to me because I've never seen it ;) I am also going to check out the JS garbage collection link too! Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.