user926958
user926958

Reputation: 9565

Javascript closure explanation with code sample

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?

Upvotes: 1

Views: 245

Answers (2)

Mario
Mario

Reputation: 3313

The quickest explanation is: a closure is created around a function and not around a statement!

Try this to know what it means:

function createClosure(item, val) {
    return function() {alert(item + ' ' + val)};
}

function buildList(list) {
 var result = [];
  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push( createClosure(item, list[i]) );
  }
  return result;
}

Upvotes: 0

Peeter
Peeter

Reputation: 9382

You do have access to all those variables. The problem is your i variable in the following loop:

  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push( function() {alert(item + ' ' + list[i])} );
  }

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.

Upvotes: 1

Related Questions