0

The code below returns: 10 10 10 10 10 10 10....

How can I produce the following output? 0 1 2 3 4 5 6 7 8 9

Here is my code:

function go() {
    var procedures = [];

    for (var i = 0; i < 10; i++) {
      procedures[procedures.length] = function () {
        alert("You are now " + i + " years old");
      };
    }

    run_procs(procedures);
}

function run_procs(procs) {
    for (var i = 0; i < procs.length; i++) {
        procs[i]();
    }
}

go();

guide me please thanks ...

Timigen
  • 1,055
  • 1
  • 17
  • 33
Shark
  • 13
  • 4

1 Answers1

1

Wrap it in self-executing anonymous function

for (var i = 0; i < 10; i++) {
    (function (i) {
        procedures[procedures.length] = function () {
            alert("You are now " + i + " years old");
        }
    })(i);
}
leopik
  • 2,323
  • 2
  • 17
  • 29
  • it worked! thanks how did it happen? – Shark Apr 27 '15 at 12:18
  • In your original loop, the `i` in the alert wasn't inserted as the current value, but as a reference to the original `i` variable. At the time when you were running `procs[i]();` in `run_procs` the `i` was already 10 and so it always printed that one number. By adding the self-executing anonymous function, we created a new scope and so every time `i` is referencing to one specific value rather than the end value (in this case 10). – leopik Apr 27 '15 at 12:44