JS Closures question 1
What is wrong with this piece of code?
1
2
3
4
5
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
})
}
Solution:
It won’t work as expected, and it will print 5 five times instead of printing 0 1 2 3 4.
In this code, console.log(i) is written inside setTimeout which will execute later, once the execution of for-loop finishes, and at that time value of i will be equal to 5(exit condition of for-loop). That is why it will print 5.