title: Lifetime of JavaScript variables
body: <p>What is the lifetime of a variable in JavaScript, declared with  "var".
  I am sure, it is definitely not according to expectation.  </p>
  
  <pre><code>&lt;script&gt;
  function(){
     var a;
     var fun=function(){
       // a is accessed and modified  
       }
  }();
  
  
  &lt;/script&gt;
  </code></pre>
  
  <p>Here how and when does JavaScript garbage collect the variable <code>a</code>? Since <code>a</code> is a part of the closure of the inner function, it ideally should never get garbage collected, since the inner function <code>fun</code>, may be passed as a reference to an external context.  So <code>fun</code> should still be able to access <code>a</code> from the external context.  </p>
  
  <p>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 ?</p>