1

I read this article, but I have some issues understanding it.

var funcs = [];
for (var i = 0; i < 3; i++) {
    (function IIFE(arg) {
        funcs[arg] = function output() {
            console.log("My value: " + arg);
        };
    })(i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}

How can I explain the mechanism of this snippet?

Start: i has value of 0. IIFE gets the value of i and stores it in arg.

funcs[0] just get assigned to a function named output.

second time, when i is 1, funcs[1] gets a totally new function? Is this false?

.....

The problem is here, How does funcs[0](); know that arg was 0? How things interact?

Function output() looks up and ask IIFE function to give the required value? right? Can someone say which illustration is correct?

IIFE

By Providing this picture, for example, number 1, I mean, when funcs[0]() gets executed, output looks for arg, it doesn't find it, then goes to higher scope and finds it. each function has it's own IIFE, for example. I'n not sure how far are this from Javascript or even programming world, but help me get it!

Community
  • 1
  • 1
Meysam
  • 185
  • 1
  • 7
  • 1
    It's all about closures... https://developer.mozilla.org/en/docs/Web/JavaScript/Closures – MysterX Nov 08 '16 at 15:45
  • And picture #1 is correct. Maybe it gets clearer if you omit the name "output" from the innermost functions. It's a new function for every loop – devnull69 Nov 08 '16 at 15:47
  • Illustration 1 is fine. But notice that it's not so much about functions being "nested", the important thing is about *scopes*. Multiple calls to even the same function will create multiple different scopes. – Bergi Nov 08 '16 at 15:48
  • 1
    *"second time, when `i` is 1, `funcs[1]` gets a totally new function?"* Exactly correct, it gets a new function. *"How does `funcs[0]();` know that `arg` was 0? How things interact?"* Because `funcs[0]` has a reference to the execution context of the call to your anonymous function that created it, which contains the `arg` related to that call. Each function created and stored in `funcs` is a *closure* over its specific `arg`. There are multiple `arg`s (one per call). See the dupetarget and MysterX's link for details. – T.J. Crowder Nov 08 '16 at 15:50
  • @Bergi: Not *scope*, execution context and associated binding object. But it's a fairly pedantic point, like formal parameter (the thing declared on the function) vs. argument (the thing it actually receives). – T.J. Crowder Nov 08 '16 at 15:51

0 Answers0