Last night I devoured the book. You Don't Know JS: Scope & Closures.
In the fifth chapter, on Scope Closures, it gives an example of how the mechanism of scope in javascript can cause a for
loop to act in unpredictable ways.
According to the text the following for loop displays the number 6
five times.
for(var i=1; i<=5; i++) { setTimeout( function timer(){ console.log( i ); }, i*1000 ); }
This problem is solved by creating a variable j
inside of the function timer()
that references the current value of i
at the time of running of that particular instance of the loop.
for (var i=1; i<=5; i++) { (function(){ var j = i; setTimeout( function timer(){ console.log( j ); }, j*1000 ); })(); }
I can accept this as is and remember to always observe this peculiarity, but I would much rather understand why.
Would someone be kind enough to provide a detailed explanation within the context of the compiler, the engine, and scope as to why the first loop doesn't work?