0

Since we know local variable of normal function dies or garbage got collected after the function finishes the execution?

So in case of closure When and how outer function local variable dies? as Closure have access of local variables of outer function.

(function outer(args) {
    var greet = "hello";
  //return inner();
    function inner() {
    console.log("inner function / closure " + greet + " " + args);
  }
})("hi");

When the outer function finish its execution, will the greet variable dies or its garbage will be collected? since it is being used in inner function.

After Edit: Actually my question concern is, we all read when function finishes its execution local variable got garbage collected or free its memory.

In case of closure any how if inner function is going to use outer function's local variable then this concept got failed ?

Sunil Madan
  • 457
  • 1
  • 4
  • 17
  • Inner function has not done its execution and any variable outside the scope of the function is _accessible_ inside the function.. – Rayon Sep 20 '16 at 16:39
  • In Objective-C, the closure (block) gets moved to the heap, and anything referred to by the closure has its reference count incremented, so the execution context of the closure is retained. I imagine something similar at work in JS. – danh Sep 20 '16 at 16:40
  • well, you sort of answered it `as Closure have access of local variables of outer function.` - they don't. Not until the closure goes. GC will collect anything that has no more pointers to it, so if the closure gets GC'd then the variable in it will be gone. If you have a reference to the inner function that has a reference to the outer scope. – VLAZ Sep 20 '16 at 16:40
  • http://stackoverflow.com/questions/19798803/how-javascript-closures-are-garbage-collected – Bergi Sep 20 '16 at 16:58

0 Answers0