This is the code example of JS Closure concept.
function buildFunctions() {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push((function(j) {
return function() {
console.log(j);
}
}(i)));
}
return arr;
}
var fn = buildFunctions();
fn[0]();
fn[1]();
fn[2]();
In this code i know when the loops starts to run and for each 'i' value(for each IIFE) new execution context with variables j=1,2,3 will be created respectively in JS engine. So when the loops finishes, the three returned functions from the 3 IIFE will sit in the var arr and the execution context of respective IIFE's will be gone but still having their variable environment with j=1,2,3 in the closure. So, now the arr will have
var arr = [function{console.log(j)},function{console.log(j)},function{console.log(j)}]
My question is how the invoking of these functions in the array, fn[0]()
picks j=0, fn[1]()
picks j=1, fn[2]()
picks j=2 from the closure respectively.?
If something is wrong in my understanding please help me...
y
variable that is in its scope. Notice there are multipley
variables (with the different values) in multiple scopes (that were created by each invocation of that IEFE). – Bergi