I am trying to understand the javascript closure. I read a example code:
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;
}
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]();
}
This code will print out “item3 undefined” alert 3 times. I do understand the “3” from the item variable at line 5, but I do not understand why does it print out “undefined” from the list[i] at line 5? Isn’t this also uses the closure to access the list variable? Could some one explain this?
You do have access to all those variables. The problem is your i variable in the following loop:
The i is passed by reference and is increased every loop. So after you’ve pushed the closure to the loop 3 times i’s value is 4 and every callback tries to alert the 4th element of [1,2,3] (the array you provided), which is undefined.