title: Why doesn't my use of "let" prevent the classic closure problem with setTimeout and consecutive variables?
body: <p>See this code:</p>
  
  <pre><code>for(var i = 0; i &lt; 5; i++) {
      setTimeout(function() {
          console.log(i);
      }, 200);
  }
  </code></pre>
  
  <p>This is the classic bug where it prints the final value of <code>i</code> repeatedly instead of printing the desired consecutive output.</p>
  
  <p>I know it can be fixed like so by using <code>let</code> instead of <code>var</code>:</p>
  
  <pre><code>for(let i = 0; i &lt; 5; i++) {
      setTimeout(function() {
          console.log(i);
      }, 200);
  }
  </code></pre>
  
  <p>What confuses me is why this <em>doesn't</em> fix it:</p>
  
  <pre><code>for(var i = 0; i &lt; 5; i++) {
      setTimeout(function() {
          let n = i;
          console.log(n);
      }, 200);
  }
  </code></pre>
  
  <p>Now it should be fixed for the same reason as the previous code, but the bug persists. Why is that?</p>