title: JavaScript Memory leak from closure lexical environment
body: <p>I am trying to understand why the following code causes a memory leak </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var aThing = null;
  var outer = function() {
  
      console.log('running');
      var something = aThing;
  
      var closure1 = function() {
          if (something) {
              console.log('something');
          }
      };
  
      aThing = {
          str: new Array(1000000).join('8'),
          someMethod: function() {}
      };
  };
  setInterval(outer, 1000);</code></pre>
  </div>
  </div>
  </p>
  
  <p>Here is the timeline showing memory increasing from Google Chrome:</p>
  
  <p><a href="https://i.stack.imgur.com/UNgC0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UNgC0.png" alt="Memory Leak"></a></p>
  
  <p>but this code which is a very slight variation does not cause the same memory leak:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var aThing = null;
  var outer = function() {
  
      console.log('running');
      var something = aThing;
      var closure1 = function() {
          if (something) {
              console.log('something');
          }
      }
  
      aThing = {
          str: new Array(1000000).join('8')
      };
  
      function someMethod() {};
  };
  setInterval(outer, 1000);</code></pre>
  </div>
  </div>
  </p>
  
  <p>Here is the equivalent timeline showing that GC is cleaning up OK. </p>
  
  <p><a href="https://i.stack.imgur.com/6SV2n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6SV2n.png" alt="No leak"></a></p>
  
  <p>I understand that in the first version there is a memory leak because the variable 'something' does not get cleaned up. Why is it being GC'ed in the second example but not the first?</p>