0

I am confused why the following code snippet has (i) at the end of it:

for (var i = 0; i < 10; i += 1) {
  (function(i) { 
    setTimeout(function() {
      console.log(i);
    }, 1000);
  })(i);
}  

Ive seen it in production code Ive worked on--I just can intuit why it's necessary.

redress
  • 1,399
  • 4
  • 20
  • 34

2 Answers2

1

Because you are defining a function inside the parenthesis, and then you are calling it passing i as parameter.

If you didn't put the (i) there, you would just define a function but never call it.

rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

You are defining an inline function, so you could force the i parameter to be in the local scope at the time of the execution of the console.log statement. By adding the parameter, you are creating a self executing function. Similar would be the following statements, which might be better to read...

function logmeWithTimeOut(value) {
    setTimeout(function() { console.log(value); }, 1000);
}

for (var i = 0; i < 10; i++) {
    logmeWithTimeout(i);
}

Though I might prefer

function logmeWithTimeout(value) {
     console.log(value);
}

for (var i = 0; i < 10; i++) {
    setTimeout(logmeWithTimeout.bind(undefined, i), 1000);
}

It forces the i to be in local scope, otherwise your log would print only 11

Icepickle
  • 12,689
  • 3
  • 34
  • 48