JSFiddle - React, Tailwind, and code Playground
JavaScript
var numberOfFunctionsRequired = 3;
var getLoopPrinter = function() {
var loopCountingFunctions = new Array(numberOfFunctionsRequired);
for (var i = 0; i < numberOfFunctionsRequired; i++) {
loopCountingFunctions[i] = (function printLoopCount() {
// What you see here is that each time this code is run, it prints the last value of the loop counter i.
// Clearly showing that for each new printLoopCount function created and saved to the loopCountingFunctions array,
// the variable i is saved to the Environment record, not the value of the variable i.
alert(i);
});
}
return loopCountingFunctions;
};
var runLoopPrinter = getLoopPrinter();
runLoopPrinter[0](); // 3
runLoopPrinter[1](); // 3
runLoopPrinter[2](); // 3