0

I have code on JavaScript.

var a = [];

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

a[2]();

If I invoke a[2]() I expect to see a message with 2 but instead of this I see 5.

To fix it I can rewrite it like this:

for (var i = 0; i < 5; i++) {
    (function (v) {
        a[i] = function () {
            alert(v);
        }
    })(i)
}

But I cannot understand how does it work. So why I need to wrap my function code to closure?

Finkelson
  • 2,921
  • 4
  • 31
  • 49
  • 3
    Because, contrary to other languages, *there is no implicit scope within `for` statements in JS.* Anonymous functions, on the other hand, have their own scope and capture outer locals, so wrapping the loop body inside a function and calling it right away solves the problem. – Frédéric Hamidi Sep 05 '16 at 22:11
  • Note also that in this case, *i* is global. – RobG Sep 05 '16 at 22:16
  • @RobG, to the outer scope. We don't know what it is -- it could be the global scope, or within a function, or even another closure. – Frédéric Hamidi Sep 05 '16 at 22:19
  • Yes, you need closures. Your code created just array of five functions and each returns last value of variable i. Because variable i is global and in each function you are alerting value of this global. –  Sep 05 '16 at 22:20
  • 1
    @WaldemarIce: No, the way closures work is *the problem*. What the OP needs is *scope*, not closures. – Felix Kling Sep 05 '16 at 22:31
  • 1
    *"But I cannot understand how does it work."* Other languages have block scope, JavaScript has function scope. To create a new scope you need to call a function. Hence if we want to create a new scope in each iteration, we need to call a function in each iteration of the loop. The variables that should be scoped to a single iteration are passed as arguments. – Felix Kling Sep 05 '16 at 22:33
  • Hence if we want to create a new scope in each iteration, we need to call a function in each iteration of the loop. <- YES. And that function creates scope, in which we create desired function, which will return value through closure... Or have you better solution as in my example? –  Sep 05 '16 at 22:42
  • @Frédéric Hamidi—closures are usually explained from within function scope. This case is a little different in that respect, though the result is the same. – RobG Sep 05 '16 at 22:52
  • @WaldemarIce: *"in which we create desired function, which will return value through closure"* Sure, the inner function needs to be a closure, but the OP already has that one. We just have to define it in a different scope. – Felix Kling Sep 06 '16 at 03:59

0 Answers0