title: How are closures and scopes represented at run time in JavaScript
body: <p>This is mostly an out-of-curiosity question.  Consider the following functions</p>
  
  <pre><code>var closure ;
  function f0() {
      var x = new BigObject() ;
      var y = 0 ;
      closure = function(){ return 7; } ;
  }
  function f1() {
      var x = BigObject() ;
      closure =  (function(y) { return function(){return y++;} ; })(0) ;
  }
  function f2() {
      var x = BigObject() ;
      var y = 0 ;
      closure = function(){ return y++ ; } ;
  }
  </code></pre>
  
  <p>In every case, after the function has been executed, there is (I think) no way to reach <em>x</em> and so the <em>BigObject</em> can be garbage collected, as long as <em>x</em> is the last reference to it.  A simple minded interpreter would capture the whole scope chain whenever a function expression is evaluated.  (For one thing, you need to do this to make calls to <em>eval</em> work -- example below).  A smarter implementation might avoid this in f0 and f1. An even smarter implementation would allow <em>y</em> to be retained, but not <em>x</em>, as is needed for f2 to be efficient.</p>
  
  <p>My question is how do the modern JavaScript engines (JaegerMonkey, V8, etc.) deal with these situations?</p>
  
  <p>Finally, here is an example that shows that variables may need to be retained even if they are never mentioned in the nested function.</p>
  
  <pre><code>var f = (function(x, y){ return function(str) { return eval(str) ; } } )(4, 5) ;
  f("1+2") ; // 3
  f("x+y") ; // 9
  f("x=6") ;
  f("x+y") ; // 11
  </code></pre>
  
  <p>However, there are restrictions that prevent one from sneaking in a call to eval in ways that might be missed by the compiler.</p>