I'm reading an article on how closures work. I'm understanding almost all of it except for Section 5 in that article.
It's talking about how closures work with loops with this example:
function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + list[i];
result.push( function() {alert(item + ' ' + list[i])} );
}
return result;
}
function testList() {
var fnlist = buildList([1,2,3]);
// using j only to help prevent confusion - could use i
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}
testList();
Three alerts come up, each saying item3 undefined. I do understand why it says item 3
. The closure from the buildList
function holds a reference to item
, it doesn't hold the actual value.
What I don't get is why list[i]
comes back as undefined
in each alert from the result.push...
line. Doesn't that closure still have the list
parameter from retained?