I know it is a classic js question:
(My question is not how to solve this problem, but how IIFE solve this problem. Thanks for the other answer link but I didn't find the answer I want)
for(var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
},1000)
}
This will print out five consecutive 5, and one way to avoid that is to create IIFE in setTimeout, I know it creates a closure but still why? Can someone give a more specific explanation about it?
Also why can't I just pass a parameter to the function?
for(var i = 0; i < 5; i++) {
setTimeout(function(i) {
console.log(i);
},1000)
}
This prints out 5 undefined...I got more confused, why is that?