JSFiddle - React, Tailwind, and code Playground
HTML
<div id="outputCreatFunction">function creatFunctions is defined first</div>
<div id="outputGlobal">variables are defined second + assigned + function creatFunctions gets called</div>
<div id="outputCreatClosure">executed + function call</div>
CSS
h2 { color: #000; }
h4 { color: #333; }
JavaScript
// 1. global function is assigned
function creatFunctions() {
var result = []; // new Array()
outputCreatFunction.innerHTML += "<h4>1.1 var result=empty " + typeof result + "</h4>";
for (var i = 0; i < 10; i++) {
// the i from for loop => better do result.push(function(){return i;})
outputCreatFunction.innerHTML += "<h4>1.2." + (i+1) + " result["+i+"]=function(){/*closure*/}</h4>";
result[i] = function () {
// not the i from the for loop because result[i] = function(){/*closure*/}
return i;
};
}
outputCreatFunction.innerHTML += "<h4 style='color: red;'>1.3 after array result is filled with functions => var i=" + i + "</h4>";
outputCreatFunction.innerHTML += "<h4>1.4 return result => length=" + result.length + "</h4>";
return result;
}
// 2. global variables
var outputCreatFunction = document.getElementById('outputCreatFunction'),
outputGlobal = document.getElementById('outputGlobal'),
outputCreatClosure = document.getElementById('outputCreatClosure');
outputCreatFunction.innerHTML = "<h2>1. outputCreatFunction</h2>";
outputGlobal.innerHTML = "<h2>2. outputGlobal</h2>";
outputCreatClosure.innerHTML = "<h2>3. outputCreatClosure</h2>";
var funcs = creatFunctions();
outputGlobal.innerHTML += "<h4>2.1 var funcs is now an array => length=" + funcs.length + "</h4>";
// 3. call enclosered function which returns => see 1.3
for (var i = 0; i < funcs.length; i++) {
// in here i is merely an index for the array result => see 1.4
outputCreatClosure.innerHTML += "<h4>3."+(i+1)+" => array func[" + i + "] gets called and returns var i from creatFunctions => " + funcs[i]() + "</h4>";
}