The following snippet is from "Example 5" from this thread on JS and closure. Alternatively, this other thread sort of gets at what I'm curious about.
function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + i;
result.push( function() {alert(item + ' ' + list[i])} );
}
return result;
}
function testList() {
var fnlist = buildList([1,2,3]);
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}
The thread this snippet is from says the output is: "item3 undefined"x3. I understand why "item3" is printed all three times, but I don't understand why list[i]
is undefined.
My Question: since list is a parameter of buildList, does that mean it's not a part of the closure of the anonymous function within result.push? If there were a variable within buildList (otherList) which was set to list (and the anonymous function used otherList[i]), would otherList[i] be in the closure? (Therefore instead of "item3 undefined"x3, the output would be "item3 3"x3).