title: Javascript: Creating Functions in a For Loop
body: <p>Recently, I found myself needing to create an array of functions.  The functions use values from an XML document, and I am running through the appropriate nodes with a for loop.  However, upon doing this, I found that only the last node of the XML sheet (corresponding to the last run of the for loop) was ever used by all of the functions in the array.</p>
  
  <p>The following is an example that showcases this:</p>
  
  <pre><code>var numArr = [];
  var funArr = [];
  for(var i = 0; i &lt; 10; ++i){
      numArr[numArr.length] = i;
      funArr[funArr.length] = function(){  return i; };
  }
  
  window.alert("Num: " + numArr[5] + "\nFun: " + funArr[5]());
  </code></pre>
  
  <p>The output is Num: 5 and Fun: 10.</p>
  
  <p>Upon research, I found a <a href="https://stackoverflow.com/questions/10813773/function-not-executed-when-creating-objects-in-a-loop-javascript">a segment of code that works</a>, but I am struggling to understand precisely why it works.  I reproduced it here using my example:</p>
  
  <pre><code>var funArr2 = [];
  for(var i = 0; i &lt; 10; ++i)
      funArr2[funArr2.length] = (function(i){ return function(){ return i;}})(i);
  
  window.alert("Fun 2: " + funArr2[5]());
  </code></pre>
  
  <p>I know it has to do with scoping, but at first glance it does not seem like it would perform any differently from my naive approach.  I am somewhat of a beginner in Javascript, so if I may ask, why is it that using this function-returning-a-function technique bypasses the scoping issue? Also, why is the (i) included on the end?</p>
  
  <p>Thank you very much in advance.</p>