0

I've read "JavaScript. The Core by Dmitry Soshnikov" and i don't understand very well this code (refactoring). Why k is increment ?

var data = [];

for (var k = 0; k < 3; k++) {
  data[k] = (function () {
    console.log(k);
  })(k)
}

data[0];
data[1];
data[2];

this portion of code :

(function () {
    console.log(k);
})(k)

So when we add a parameter (k) to the end of a function, if i understand well, the value (k) is take from the current context/scope ?

Brice Chaponneau
  • 564
  • 2
  • 9
  • 22
  • 2
    That code would *work* but it doesn't make much sense as an example; it doesn't do anything. The array will be populated with `undefined` because the function returns nothing. – Pointy Sep 19 '18 at 13:23
  • 2
    ... nor does it accept any arguments – Phil Sep 19 '18 at 13:24
  • 2
    ... and therefore would be exactly the same with `()` as with `(k)`. – Scott Sauyet Sep 19 '18 at 13:24
  • @Pointy: it does do something. It logs the values to the console and fills the array with three `undefined`s. But this is very odd. I haven't yet looked at that book, so I don't know what it's trying to show here, but I know the author knows his stuff. – Scott Sauyet Sep 19 '18 at 13:27
  • The code posted here does not appear in the article referenced. Code *like* the posted code appears, but not exactly this code. The examples in the article do make sense. – Pointy Sep 19 '18 at 13:31
  • 1
    Ok i understand. It's an auto execute function : IIFE ! – Brice Chaponneau Sep 19 '18 at 13:33

0 Answers0