title: How does a function in a loop (which returns another function) work?
body: <p>I've been trying to assign a function to <code>onclick</code> event of a dynamically created &quot;a&quot; tag in JavaScript. All of the tags are created in a loop as follows:</p>
  <pre><code>for ( var i = 0; i &lt; 4; i++ )
  {
    var a = document.createElement( &quot;a&quot; );
    a.onclick = function( ) { alert( i ) };
    document.getElementById( &quot;foo&quot; ).appendChild( a );
  }
  </code></pre>
  <p>The alerted value for all four links is always &quot;4&quot;. Pretty obvious. When googling I came across a post that shows the following code snippet:</p>
  <pre><code>a.onclick = (function(p, d) {
  return function(){ show_photo(p, d) }
  })(path, description);
  </code></pre>
  <p>I managed to tweak it for my needs and got the alert( i ) thing to work correctly but I'll appreciate if someone could explain exactly what the above code does.</p>