So I was reading You Don't Know Javascript: Closures and Scope Chapter 5 and I came upon this code:
for (var i=1; i<=5; i++) {
setTimeout( function timer(){
console.log( i );
}, i*1000 );
}
I failed to understand why does this print '6' 5 times. According to me: i=0 -> we come upon setTimeout and console.log(i) should print 0, wait for 1 second, and then one iteration of the for loop is completed. The next time the loop runs, i will = 2 and so on and so forth.
Help will be appreciated :)