Create closure inside loops in javascript

When you use loop having a iteration variable like "i" and changing the value of "i" then all the closure access same variable and the variable value changed. Here you will face the problem that all the closure will take last value of "i".

For eg.

var funcs = [];
for (var i = 0; i < 10; i++) {
  funcs[i] = function() {          
    console.log("Getting Value: " + i);
  };
}
for (var j = 0; j < 10; j++) {
  funcs[j]();                      
}

Output:

Getting Value: 10
Getting Value: 10
Getting Value: 10
Getting Value: 10
Getting Value: 10
Getting Value: 10
Getting Value: 10
Getting Value: 10
Getting Value: 10
Getting Value: 10

Solution 1:

Put closure creator function outside the loop so that individual local value can be store in closure.

var funcs = [];

function createfunc(i) {
    return function() { console.log("Current value: " + i); };
}

for (var i = 0; i < 10; i++) {
    funcs[i] = createfunc(i);
}

for (var j = 0; j < 10; j++) {
    funcs[j]();               
}

 

Solution 2:

If you are using ES6 the change the var into let for variable diclaration in for loop.

var funcs = [];
for (let i = 0; i < 10; i++) {
  funcs[i] = function() {          
    console.log("Getting Value: " + i);
  };
}
for (var j = 0; j < 10; j++) {
  funcs[j]();                      
}

 

 Output:

Getting Value: 0
Getting Value: 1
Getting Value: 2
Getting Value: 3
Getting Value: 4
Getting Value: 5
Getting Value: 6
Getting Value: 7
Getting Value: 8
Getting Value: 9


Keywords: