var arr = []
for (var i = 0; i < 5; i++) {
arr[i] = function(id) {
return function() {
return id;
}
}(i);
}
for (var index in arr) {
console.log(arr[index]());
}
My thinking: 'I' which is in the (i); will refer to a global variable 'I'. 'I' which is in the (i); will be saved in the 'id' which is in the function(id). 'id' is a local variable of outer function. 'id' which is in the inner function will refer to 'id' which is a local variable of outer function. Then, the result is '0,1,2,3,4'. But I think I can get the same result without outer function.
var arr = []
for (var i = 0; i < 5; i++) {
arr[i] = function(id) {
return id;
}(i);
}
for (var index in arr) {
console.log(arr[index]());
}
In this case, 'I' which is in the (i); will refer to 'I' which is a global variable. 'I' which is in the (i); will be saved in 'id' which is a local variable of function. 'id' which is behind return code will refer to 'id' which is a local variable of function. Then, the result is '0,1,2,3,4'. Using outer function like the first code is unnecessary because the second code is possible. Am I right?