closure on a variable modified in loop code example
Example 1: javascript closure inside loop
var funcs = [];
function createfunc(i) {
return function() {
console.log("My value: " + i);
};
}
for (var i = 0; i < 3; i++) {
funcs[i] = createfunc(i);
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}
Example 2: How Closure works totally different in Loop!!!!
Explanation From Medium:
//https://medium.com/brandsoft/variable-scope-and-iifes-in-javascript-3cf85f79597e#:~:text=By%20using%20an%20IIFE%2C%20we,when%20the%20IIFE%20is%20executed.
Code:
// for (var i = 0; i<=5; i++){ // this type of problem created
// setTimeout(function (){
// console.log('Current Value is ' + i);
// }, 1000 * i)
// }
// for (var i = 0; i <= 5; i++) {
// (function (n) { // to avoid previous example's fault
// setTimeout(function () {
// console.log('Current Value is ' + n);
// }, 1000 * n)
// })(i);
// }
// for (let i = 0; i<=5; i++){ // in this case (let) behaves different from var
// setTimeout(function (){
// console.log(i);
// }, 1000 * i)
// }