0

This is an exercise from "Object oriented javascript" in the section about closures. I'm having trouble understanding the need for the highlighted extra function used to "return x;". Tried using return x; directly from the function accepting the parameter x and it doesn't work but I can't grasp why it makes it work. Thanks

function F() {
  var arr = [], i;
  for (i = 0; i < 3; i++) {
    arr[i] = (function (x) {
      **return function ()** {
        return x;
      };
    }(i));
  }
  return arr;
}


> var arr = F();
> arr[0]();
0
> arr[1]();
1
> arr[2]();
2
mvelazquez
  • 171
  • 1
  • 7
  • it makes _i_ "private" inside as _x_, otherwise x would ~always == the last value of _i_ – dandavis Sep 13 '14 at 22:39
  • Common question http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – elclanrs Sep 13 '14 at 22:39

0 Answers0