title: Weird Output with ES6 closures containing nested functions and loops, Why is output different with Var and different with Let?
body: <pre><code>function makeFunctionArray(){
      const arr=[]
  
      for(var i = 0; i &lt; 5; i++){
          arr.push(function(){console.log(i)})
      }
      return arr
  }
  
  const functionArr = makeFunctionArray()
  
  functionArr[0]()
  </code></pre>
  
  <p>Can someone explain to me why functionArray[0] prints out 5 instead of 0? I get that using var i = 0 in the for loop means that i = 5 after the for loop ends (due to scope), but I don't see how that changes the first item in the array to be 5 instead of 0. Using let instead of var for i gives the right answer, but I can't wrap my head around as to why.</p>