title: Behavior of let variables declared inside for loop in context of closures
body: <p>In below snippet, the function passed to <code>setTimeout</code> forms a closure with the variable <code>i</code> which is present in the <code>script</code> scope. So the function contains a <em>reference</em> to variable <code>i</code>. The value of <code>i</code> is updated to 5 before <code>i</code> is logged to console. And the output is: <code>5 5 5 5 5</code> (with newlines)</p>
  <p><code>script.js</code>:</p>
  <pre class="lang-js prettyprint-override"><code>let i;
  for (i = 0; i &lt; 5; ++i) {
      setTimeout(() =&gt; {
          console.log(i);
      }, i * 1000);
  }
  </code></pre>
  <p>The above part is clear to me. <strong>But</strong> when I declare variable <code>i</code> <em>inside</em> <code>for</code> loop, then <code>i</code> is block scoped to the <code>for</code> loop.</p>
  <pre class="lang-js prettyprint-override"><code>for (let i = 0; i &lt; 5; ++i) {
      setTimeout(() =&gt; {
          console.log(i);
      }, i * 1000);
  }
  </code></pre>
  <p>In this code snippet, I expect the output to be same as output of first snippet, because the closure contains <em>reference</em> to the variable <code>i</code> and the value at that <em>reference</em> should be updated to 5 before the value is logged to console. But the actual output is: <code>0 1 2 3 4</code> (with newlines)</p>
  <p>The question is, why the code in second snippet behaves this way?</p>
  <p>It it because:</p>
  <ol>
  <li>A new copy of variable <code>i</code> is created in memory for each iteration of <code>for</code> loop and previous copy is garbage collected? I'm not sure how memory management works for loops.</li>
  <li>Instead of storing reference of <code>i</code>, the <em>value</em> of <code>i</code> is stored in closure? I don't think this is the case.</li>
  <li>Anything else?</li>
  </ol>
  <p>Please help to clarify. Thanks!</p>