Loops and closure Javascript
<p>This code below is extracted from You don't know "JavaScript : Scopes and Closures" book by Kyle Simpson.</p>

<pre><code>for (var i=1; i&lt;=5; i++) {
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}
</code></pre>

<p>The author talks about how it will print the the number 6 five times every second but doesn't quite explain why.</p>

<p>From my point of view, I see the function timer() inside function setTimeout() and also know that the timer() covers the scope of its outer function too. If the code had something extra like this:</p>

<pre><code>for (..) {...};
var foo = setTimeout(something);
foo();
</code></pre>

<p>In this case, foo() has the function timer() stored in it as a value (function object I suppose). So upon execution, it prints out whatever code is inside timer() function.</p>

<p>However, in the example given by the author there are no such steps and I can't quite get my head around over how the code is working internally and why it print 6 five times. The for-loop is confusing me even more. I would greatly love to how the process is working internally inside Javascript hood.</p>