1

Why is running f1 different in Version B than in Version A, below?
// Version A

var f = {};
for( var i=0 ; i<3 ; i++ ) {
f[i] = function() { alert(i); }
}

// Version B

var f = {};
for( var i=0 ; i<3 ; i++ ) {
f[i] = function(j) { return function() { alert(j); }; }(i);
}
Sea guy
  • 178
  • 1
  • 2
  • 10
  • http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – georg Aug 05 '13 at 11:23

2 Answers2

4

The first code snippet makes 3 functions that are bound to i.

The second code snippet makes 3 functions that are closed around the value of i - a closure.

This means that in the first example, if you do:

i = "hi";
f[0](); // "hi"

Minor:

f should probably be initialized as f = [] since you're using it as an array.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
0

This is because of a concept called as a closure where the values of the parameters of the function returning the function are preserved in the returned function

shyam
  • 9,134
  • 4
  • 29
  • 44