Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Answer

Post Timeline

Till ES5, This problem can only be solved using closure.

But now in ES6, we have block level scope variables. Changing var to let in first for loop will solve the problem.

var funcs = [];
for (let i = 0; i < 3; i++) { // let's create 3 functions
 funcs[i] = function() { // and store them in funcs
 console.log("My value: " + i); // each should log its value.
 };
}
for (var j = 0; j < 3; j++) {
 funcs[j](); // and now let's run each one to see
}

var funcs = [];
for (let i = 0; i < 3; i++) { // let's create 3 functions
 funcs[i] = function() { // and store them in funcs
 console.log("My value: " + i); // each should log its value.
 };
}
for (var j = 0; j < 3; j++) {
 funcs[j](); // and now let's run each one to see
}

Till ES5, This problem can only be solved using closure.

But now in ES6, we have block level scope variables. Changing var to let in first for loop will solve the problem.

var funcs = [];
for (let i = 0; i < 3; i++) { // let's create 3 functions
 funcs[i] = function() { // and store them in funcs
 console.log("My value: " + i); // each should log its value.
 };
}
for (var j = 0; j < 3; j++) {
 funcs[j](); // and now let's run each one to see
}

Till ES5, This problem can only be solved using closure.

But now in ES6, we have block level scope variables. Changing var to let in first for loop will solve the problem.

var funcs = [];
for (let i = 0; i < 3; i++) { // let's create 3 functions
 funcs[i] = function() { // and store them in funcs
 console.log("My value: " + i); // each should log its value.
 };
}
for (var j = 0; j < 3; j++) {
 funcs[j](); // and now let's run each one to see
}

Source Link
Shivang Gupta
  • 3.4k
  • 1
  • 28
  • 25

Till ES5, This problem can only be solved using closure.

But now in ES6, we have block level scope variables. Changing var to let in first for loop will solve the problem.

var funcs = [];
for (let i = 0; i < 3; i++) { // let's create 3 functions
 funcs[i] = function() { // and store them in funcs
 console.log("My value: " + i); // each should log its value.
 };
}
for (var j = 0; j < 3; j++) {
 funcs[j](); // and now let's run each one to see
}
lang-js

AltStyle によって変換されたページ (->オリジナル) /