1

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?

윤성우
  • 11
  • 2
  • 1
    Because you are using `var` instead of `let`. – elclanrs Jun 11 '21 at 02:56
  • Possible duplicate of https://stackoverflow.com/q/12930272/12101554 – Samathingamajig Jun 11 '21 at 03:06
  • 1
    "*Am I wrong?*" clearly the second code throws an error, so I guess the answer is "yes". The problem is that in the second case you don't assign *functions* as members of the array, you *execute* a function and assign the result. So the array is `[0, 1, 2, 3, 4]` not functions that will return those values. – VLAZ Jun 11 '21 at 05:07

1 Answers1

0

You could even not use any function at all, and just set arr[i] = i. But something tells me that you've simplified the supplied code in such a way that the reason for using such a pattern was removed.

This kind of function pattern is called partial function application, where you apply some parameters to a function and get back another function of smaller arity. In such a case as what you've shown, one benefit of this approach is saving the execution of a result function to be called later, but applying the known parameters before that time.

j1mbl3s
  • 994
  • 3
  • 16
  • I think it depends on what you are trying to accomplish. Do you want an immediate result, or do you want to just apply a few parameters and save the computation of the result for later? If there is no reason to hold off on computing a result, I would recommend reducing the complexity and set the result immdiately. – j1mbl3s Jun 11 '21 at 08:23