You and your friend both use closures:
A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.
MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures
In your friend's code function function(){ console.log(i2); }
defined inside closure of anonymous function function(){ var i2 = i; ...
and can read/write local variable i2
.
In your code function function(){ console.log(i2); }
defined inside closure of function function(i2){ return ...
and can read/write local valuable i2
(declared in this case as a parameter).
In both cases function function(){ console.log(i2); }
then passed into setTimeout
.
Another equivalent (but with less memory utilization) is:
function fGenerator(i2){
return function(){
console.log(i2);
}
}
for(var i = 0; i < 10; i++) {
setTimeout(fGenerator(i), 1000);
}