1

The following code is supposed to log the correct number of button pressed. And it is supposedly does.

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', (function(i) {
    return function() { console.log(i); };
  })(i)); //line 4!
  document.body.appendChild(btn);
}

What I don't get is what is the use of (i) on the line 4. It doesn't seem to pass anywhere as for me. Tell me please what to read so I could understand this.

TheKitMurkit
  • 463
  • 7
  • 17
  • 1
    It's [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) because in javascript loops don't introduce new scope only functions does, so you need one of those to create new scope with i variable – jcubic Sep 26 '16 at 14:38
  • since the scope `i` of the function is a variable definition for the scope of that function, you need to pass in the reference to `i` by telling that it will pass in the number immediately do that function, so it would understand what i is. – Fallenreaper Sep 26 '16 at 14:40

0 Answers0