re: JavaScript Closure Simply Explained VIEW POST

FULL DISCUSSION
 

The code in the final example is actually wrong:

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

If you write like this, you might as well remove setTimeout completely as it's not doing anything here (try setting timeout to 10s and see if it prints out the result after 10s).
What you are doing is this:

function printIndex(index) {
  console.log(index)
}

for(var i=0; i<5; i++) {
  setTimeout(printIndex(i), 1000)
}

This will just print out all index immediately and setTimeout will have no effect.
To fix this - you either need to return a function, or using bind when setting a timeout, e.g.:

function printIndex(index) {
  return () => console.log(index)
}

for(var i=0; i<5; i++) {
  setTimeout(printIndex(i), 1000)
}
 

Oops. you are totally correct, forgot to return a function!. I appreciate you pointing this out. Will fix the code example!

code of conduct - report abuse