9

What is the lifetime of a variable in JavaScript, declared with "var". I am sure, it is definitely not according to expectation.

<script>
function(){
   var a;
   var fun=function(){
     // a is accessed and modified  
     }
}();


</script>

Here how and when does JavaScript garbage collect the variable a? Since a is a part of the closure of the inner function, it ideally should never get garbage collected, since the inner function fun, may be passed as a reference to an external context. So fun should still be able to access a from the external context.

If my understanding is correct, how does garbage collection happen then, and how does it ensure to have enough memory space, since keeping all variables in memory until the execution of the program might not be tenable ?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
The Machine
  • 1,221
  • 4
  • 14
  • 27
  • This is a great question btw. It points out that the closure itself isn't the only thing that is held in memory until the closure is GC'ed. The entire scope chain of the function is as well. There appears to be some controversy, but some additional thought would seem to indicate that every function declaration in JavaScript is a closure, relative to the global scope. However there is an exception [see this answer](http://stackoverflow.com/a/30252865/511795) – Shanimal Mar 17 '16 at 17:15

2 Answers2

4

The ECMAScript specification does not specify how the garbage collector should work, it only says that if an identifier is reachable (through a direct pointer or a closure), it shouldn't be GCed.

Check out this article about identifier resolution, closures, scope chaining and garbage collection in ECMAScript.

Hope it helps

artemnih
  • 4,136
  • 2
  • 18
  • 28
Pablo Cabrera
  • 5,749
  • 4
  • 23
  • 28
1

'a' will not be garbage-collected as long as there are external references to 'fun'. The browser ensures it has enough memory by asking for more memory from the OS.

Jeffery To
  • 11,836
  • 1
  • 27
  • 42