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++) {
(function (i) {
// Now what happens here is each time the above loop runs this code,
// inside this scope (the scope of this comment) i is a new formal parameter which of course
// gets statically saved to each printLoopCount functions Environment record (or more simply each closure of printLoopCount).
loopCountingFunctions[i] = (function printLoopCount() {
alert(i);
});
})(i)
}
return loopCountingFunctions;
};
var runLoopPrinter = getLoopPrinter();
runLoopPrinter[0](); // 0
runLoopPrinter[1](); // 1
runLoopPrinter[2](); // 2