title: Use IIFE in setTimeout in a loop, but why?
body: <p>I know it is a classic js question:</p>
  
  <p>(My question is not how to solve this problem, but how IIFE solve this problem. Thanks for the other answer link but I didn't find the answer I want)</p>
  
  <pre><code>for(var i = 0; i &lt; 5; i++) {
      setTimeout(function() {
          console.log(i);
      },1000)
  }
  </code></pre>
  
  <p>This will print out five consecutive 5, and one way to avoid that is to create IIFE in setTimeout, I know it creates a closure but still why? Can someone give a more specific explanation about it? </p>
  
  <p>Also why can't I just pass a parameter to the function?</p>
  
  <pre><code>for(var i = 0; i &lt; 5; i++) {
      setTimeout(function(i) {
          console.log(i);
      },1000)
  }
  </code></pre>
  
  <p>This prints out 5 undefined...I got more confused, why is that?</p>