Here is a code:
var data = [ 'data1', 'data2', 'data3' ];
for (var i = 0; i < data.length; i++) {
var x = data[i];
setTimeout(function() {
console.log(x);
}, i * 100);
}
The output is 3 times 'data3'. My question is why?
I understand that all 3 log methods will be called after the loop is finished already and variable i will be equal to 3, BUT!
I'm defining x variable inside the loop. I'm expecting on every loop iteration this variable to be recreated locally so that when every of console.log(x) methods are called they refer to 3 different variables stored in the memory.
But it looks like code:
var x = data[i];
updates the same variable instead of recreating it.
Can someone explain this behaviour please?