Anyone explain this(behavior differences between var and let in for loop) please?
classical interview question(closure):
let a = []; for (var i=0; i<10; i++) { a[i] = function() { console.log(i,); } } a[0](); // 10 a[1](); // 10
if we use let:
let a = []; for (let i=0; i<10; i++) { // var => let a[i] = function() { console.log(i); } } a[0](); // 1 a[1](); // 2
Yes, i is normal and as expected when using 'let'. The first thought came to my mind is that let doesnt support closure. But no, it supports. (following tested it on Chrome):
function bb() {
let b = 1;
return function() {
console.log(b);
}
}
bb()(); // 1, means a closure is created
Then my second explanation is: when using let in for loop. For EVERY loop, it creates a new i repeatedly. And this is proved in chrome debugger by me.
Question is:
if i is created in each loop in the for-loop. How does it keeps increasing??? Why it doesn't just keep being 0 as we declared if it is created every time?
for (let i=0; .......)