So i already learnt a lot about closures here on SO.
But i still found one examples i can't explain to myself:
function buildList(list){
var result = [];
for(var i = 0; i < list.length; i++) {
var item = "item: " + list[i] + " i's value: " + i; //i has the value of 2 here, but why?
result.push( function(){document.write(item + ", list[i]:" + list[i] + ", i's value in the anonymous function:" + i + "<br>")});
} //i = 3 here
return result;
}
function testList(){
var testTheList = buildList([1,2,3]);
for (var j = 0; j < testTheList.length; j++) {
testTheList[j]();
}
}
testList();
As i would expect of the closure, i should be 3 when i execute the testList().
But the result is:
item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3
item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3
item: 3 i's value: 2, list[i]:undefined, i's value in the anonymous function:3
Why does is i for the var item => 2 and i inside the anonymous function => 3 ? As i read, closures create new execution environments, but shouldnt i be the same value for the closure?
EDIT
This is not a duplicate of JavaScript closure inside loops – simple practical example, i don't want to know, how to create a new execution environment.
I want to know why the value of the same variable i (of the the loop) differs in the same scope?